<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;
use App\Models\Warranty;
use App\Models\WarrantyImage;
use App\Models\WarrantyMsg;
use App\Models\Permissions;
use App\Models\Admin;
use App\Models\RollRestlen;
use App\Models\RollTransfer;
use App\Models\UserAssist;
use App\Models\RollSales;
use App\Models\Precut;
use App\Models\PrecutAssign;
use App\Models\RollMaster;
use App\Models\PartMaster;
use App\Models\Roles;
use App\Models\Cities;
use App\Models\ProvinceMaster;
use App\Models\RegionMaster;
use App\Models\SmsCode;
use App\Models\MacroManagement;
use App\Models\NewPrecutPart;
use App\Models\ProductTypes;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\FilmTypeMaster;
use App\Models\WarrantyToVehicleCoverage;
use App\Models\RollReturn;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use App\Models\NewPrecut;
use App\Models\NewPrecutFpart;
use App\Models\NewPrecutCoverage;
use Illuminate\Support\Facades\Storage;

/*
 * 本地化，假如传入值与返回值一致
 * 则默认内容不存在
 * 如果内容一致时，使用原生本地化
 * */

function _t($key)
{
    $k = \Illuminate\Support\Facades\Lang::has($key);
    if ($k) {
        return \Illuminate\Support\Facades\Lang::get($key);
    }
    return '';
}
/*
 * 本地化*/
function ts($key)
{
    $key = trim($key);
    if (empty(stripos($key, '.'))) {
        $key = 'macro_management.' . strtoupper($key);
    }
    $k = \Illuminate\Support\Facades\Lang::has($key);
    if ($k) {
        return \Illuminate\Support\Facades\Lang::get($key);
    }
    return '';
}

/*
 * 文件仅存储路径，不存储host
 * 七牛云的上传文件长度为32（不含后缀）
 * 通过长度确定host
 * */
function getInstallPicture($url)
{
    $url = trim($url);
    # $host = 'http://xpel.dengwho.com/pictures/';
    $host = '/';
    if (empty($url) || $url == '/') {
        // return '/images/RLh1y8Wp.png';
        return false;
    }
    if (strpos($url, 'https') !== false || strpos($url, 'http') !== false) {
        return $url;
    }
    if (stripos($url, '/') === 0) {
        return $url;
    }
    $o = pathinfo($url, PATHINFO_FILENAME);

    if (mb_strlen($o) == 10) {
        $host = '/pictures/';
    }
    if (mb_strlen($o) == 32) {
        $host = env('QINIUYUN_SECRET_HOST');
    }
    if (mb_strlen($o) == 30) {
        $host = '/images/';
    }
    return $host . $url;
}


function makeLangFile($table)
{
    $label = 'id';
    $dir = resource_path('lang');
    $filename = $table . '.php';
    if ($table == 'cities') {
        $data = \App\Models\Cities::get();
    } elseif ($table == 'province_master') {
        $data = \App\Models\ProvinceMaster::get();
    } elseif ($table == 'region_master') {
        $data = \App\Models\RegionMaster::get();
    } elseif ($table == 'macro_management') {
        $label = 'macro_name';
        $data = MacroManagement::get();
    } elseif ($table == 'product_types') {
        $data = \App\Models\ProductTypes::get();
    } elseif ($table == 'make_master') {
        $data = \App\Models\MakeMaster::withTrashed()->get();
    } elseif ($table == 'model_master') {
        $data = \App\Models\ModelMaster::withTrashed()->get();
    } elseif ($table == 'part_master') {
        $data = \App\Models\PartMaster::withTrashed()->get();
    } elseif ($table == 'film_type_master') {
        $data = \App\Models\FilmTypeMaster::withTrashed()->get();
    } elseif ($table == 'product_type_master') {
        $data = \App\Models\ProductTypes::get();
    } elseif ($table == 'new_precut_part') {
        $data = NewPrecutPart::get();
    } else {
        return $table;
    }

    $prefix = '<?php' . "\n\n" . 'return [' . "\n";
    $suffix = '];';
    $en = $zh_tw = $zh = '';
    $en .= '    "0" => "",' . "\n";
    $zh_tw .= ' "0" => "",' . "\n";
    $zh .= '    "0" => "",' . "\n";
    foreach ($data as $k => $v) {
        $en .= '    "' . $v->$label . '" => "' .  $v->english_value . '",' . "\n";
        $zh_tw .= ' "' . $v->$label . '" => "' .  $v->traditional_chiness_value . '",' . "\n";
        $zh .= '    "' . $v->$label . '" => "' .  $v->simplified_chiness_value . '",' . "\n";
    }
    file_put_contents($dir . '/en/' . $filename, $prefix . $en . $suffix);
    file_put_contents($dir . '/zh/' . $filename, $prefix . $zh . $suffix);
    file_put_contents($dir . '/zh_tw/' . $filename, $prefix . $zh_tw . $suffix);
    return true;
}

/*
 * 1超级管理员可用权限或打开页面
 * 获取所有导航
 * 根据链接长度降序排序
 * 匹配链接（第一个匹配项），判断是否拥有该权限
 * 如果有则继续，否则跳出
 * 不判断角色123
 * 判断权限
 * */
function  checkAuthority($level = 1)
{
    $user_id = session('admin.id');
    $user_type = session('admin.user_type');
    $role_id = session('admin.role_id');
    if ($user_type == 1) {
        return true;
    }
    if (!empty($role_id)) {
        return true;
    }

    if ($user_type > 3) {
        $roles = Roles::find($user_type);
        $method = request()->method();
        [$controller, $method] = explode('@', request()->route()->getActionName(), 2);
        $admin = 'App\Http\Controllers\Admin\\';
        /*
         * 判断控制器与方法是否与数据库存储的一致*/
        if (strpos($controller, $admin) === 0) {
            $controller = substr($controller, strlen($admin));
            $allows = $roles->permissions()->get(['id', 'controller', 'methods']);
            if ($controller == 'AdminController') {
                foreach ($allows as $v) {
                    $ams = explode(',', $v->methods); // 方法
                    $acs = explode(',', $v->controller); // 控制器
                    foreach ($acs as $ack) {
                        if (trim($ack) == $controller) {
                            foreach ($ams as $amk) {
                                if (trim($amk) == $method) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // $path = \Illuminate\Support\Facades\URL::current();
    // $path = request()->path();
    // $per = Permissions::get(['id', 'url']);

    // return dd([$path]);

    // 仅管理员可以操作的内容
    /*if ($level == 1) {
        if ($user_type !== 1) {
            abort(404);
        }
    }*/
    if ($user_type !== 1) {
        abort(404);
    }
    return true;
}

/*
 * 1超级管理员可用权限或打开页面
 * 获取所有导航
 * 根据链接长度降序排序
 * 匹配链接（第一个匹配项），判断是否拥有该权限
 * 如果有则继续，否则跳出
 * 不判断角色123
 * 判断权限
 * */
function checkMethodsAuthority($method, $controller = 'AdminController')
{
    $user_id = session('admin.id');
    $user_type = session('admin.user_type');
    if ($user_type == 1) {
        return true;
    }
    if ($user_type > 3) {
        $roles = Roles::find($user_type);
        $admin = 'App\Http\Controllers\Admin\\';
        /*
         * 判断控制器与方法是否与数据库存储的一致*/
        $allows = $roles->permissions()->get(['id', 'controller', 'methods']);
        if ($controller == 'AdminController') {
            foreach ($allows as $v) {
                $ams = explode(',', $v->methods); // 方法
                $acs = explode(',', $v->controller); // 控制器
                foreach ($acs as $ack) {
                    if (trim($ack) == $controller) {
                        foreach ($ams as $amk) {
                            if (trim($amk) == $method) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        /*if (strpos($controller, $admin) === 0) {
            $controller = substr ($controller, strlen($admin));
            $allows = $roles->permissions()->get(['id', 'controller', 'methods']);
            if ($controller == 'AdminController') {
                foreach ($allows as $v) {
                    $ams = explode(',', $v->methods); // 方法
                    $acs = explode(',', $v->controller); // 控制器
                    foreach ($acs as $ack) {
                        if(trim($ack) == $controller) {
                            foreach ($ams as $amk) {
                                if(trim($amk) == $method) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }*/
    }
    return false;
}
/*
 * 日志记录
 * 按模型保存，如warranty=>coverages,precut=>coverages
 * 单记录
 * 记录后返回日志模型
 * 对于修改，开始时，new为空返回模型
 * 然后模型->new=new，保存模型*/
function alogs($module, $activity, $record, $new = null, $old = null)
{
    if (session('admin.id')) {
        $user_id = session('admin.id');
        $user_type = session('admin.user_type');
        $user_name = session('admin.username') ?: session('admin.unique_id');
    } else {
        $user = session()->get('admin');
        $user_id = @$user->id;
        $user_type = @$user->user_type;
        $user_name = @$user->username ?: session('admin.unique_id');
    }
    if (!empty($new)) {
        $new = json_encode($new);
    } else {
        $new = null;
    }
    if (!empty($old)) {
        $old = json_encode($old);
    } else {
        $old = null;
    }
    $log = new \App\Models\Activity();
    $log->user_type = $user_type;
    $log->user_id = $user_id;
    $log->user_name = $user_name;
    $log->method = request()->method();
    $log->ip = request()->ip();
    $log->url = request()->url();
    $log->input = @json_encode(request()->input());
    $log->module = $module;
    $log->activity = $activity;
    $log->record = $record;
    $log->new = $new;
    $log->old = $old;
    $log->save();
    return $log;
}
/*
 * 日志存储质保或套餐数据
 * 格式化coverage数据*/
function mmc($model, $coverages, $images = [])
{
    if (empty($model)) {
        return [];
    }
    $array = [];
    if (empty($coverages)) {
        $model->coverages = [];
    }
    // $coverages = $coverages;
    foreach ($coverages as $k => $v) {
        $v = (array) $v;
        $array[] = [
            'part_id' => @$v['part_id'],
            'roll_number' => @$v['roll_number'],
            'length' => @$v['length'],
        ];
    }
    $model->coverages = $array;
    $model->images = $images;
    return $model;
}
function mpmc($model, $coverages, $warranty)
{
    if (empty($model)) {
        return [];
    }
    $array = [];
    if (empty($coverages)) {
        $model->coverages = [];
    }
    foreach ($coverages as $k => $v) {
        $v = (array) $v;
        $array[] = [
            'part_id' => @$v['part_id'],
            'roll_number' => @$v['roll_number'],
            'length' => @$v['length'],
        ];
    }
    $model->coverages = $array;
    $model->warranty = $warranty;
    return $model;
}

/*
 * 关于日志，删除、修改时记录的是原始数据
 * 新增时记录的是新增的数据
 * 多项删除时、更新时，
 * */
function recordActivety($module, $name, $datas = null)
{
    if (session('admin.id')) {
        $user_id = session('admin.id');
    } else {
        $user = session()->get('admin');
        $user_id = @$user->id;
    }
    if ($datas === null && is_array($name)) {
        $datas = $name;
        $name = $module;
        $module = '';
    }
    $log = new \App\Models\ActivityLogs();
    $log->user_type = 1; // member
    $log->user_id = $user_id;
    $log->method = request()->method();
    $log->ip = request()->ip();
    $log->url = request()->url();
    $log->input = @json_encode(request()->input());
    $log->backup = @json_encode($datas);
    $log->activity = $name;
    $log->module = $module;
    $log->save();
}
/*
 * 记录模块、操作内容，操作ID，数据
 * name:1添加2修改3删除4发起审核5审核通过6审核拒绝7分配8调货9启用10停用11登录
 * module:1质保2卷膜3套餐4省代5经销商6膜种类7品牌8车型
 * */
function doLogs($module, $name, $records, $datas = null, $query = null)
{
    if (session('admin.id')) {
        $user_id = session('admin.id');
        $user_type = session('admin.user_type');
    } else {
        $user = session()->get('admin');
        $user_id = @$user->id;
        $user_type = @$user->user_type;
    }
    if (is_array($records)) {
        $records = implode('#', $records);
    }
    if ($datas === null && is_array($name)) {
        $datas = $name;
        $name = $module;
        $module = '';
    }
    $log = new \App\Models\ActivityLogs();
    $log->user_type = $user_type; // member
    $log->user_id = $user_id;
    $log->method = request()->method();
    $log->ip = request()->ip();
    $log->url = request()->url();
    $log->input = @json_encode(request()->input());
    $log->backup = @json_encode($datas);
    $log->activity = $name;
    $log->module = $module;
    $log->records = $records;
    // $log->query = $query;
    $log->save();
}
function doLogsL($module, $name, $records, $datas = null)
{
    if (session('admin.id')) {
        $user_id = session('admin.id');
    } else {
        $user = session()->get('admin');
        $user_id = @$user->id;
    }
    if (is_array($records)) {
        $records = implode('#', $records);
    }
    if ($datas === null && is_array($name)) {
        $datas = $name;
        $name = $module;
        $module = '';
    }
    $log = new \App\Models\ActivityLogs();
    $log->user_type = 1; // member
    $log->user_id = $user_id;
    $log->method = request()->method();
    $log->ip = request()->ip();
    $log->url = request()->url();
    $log->input = @json_encode(request()->input());
    $log->backup = @json_encode($datas);
    $log->activity = $name;
    $log->module = $module;
    $log->records = $records;
    $log->save();
}
/*
 * 数据库操作记录
 * 对于记录表不计入
 * 对于常用非主表查询不记录
 * */
function dbLogs($query)
{
    $sql = $query->sql;
    $activity = 'activity';
    $table = '';
    while (stripos($sql, '(') === 0) {
        $sql = substr($sql, 1);
    }
    if (stripos($sql, 'select') === 0) {
        $activity = 'select';
        $table = stristr($sql, ' from ');
        $table = substr($table, 7);
    }
    if (stripos($sql, 'insert') === 0) {
        $activity = 'insert';
        $table = substr($sql, 13);
    }
    if (stripos($sql, 'update') === 0) {
        $activity = 'update';
        $table = substr($sql, 8);
    }
    if (stripos($sql, 'delete') === 0) {
        $activity = 'delete';
        $table = substr($sql, 13);
    }
    $table = substr($table, 0, stripos($table, '`'));

    if ($table == 'user_sync') {
        return;
    }
    if (strtolower($activity) == 'select') {
        if (in_array($table, ['activity', 'cities', 'province_master', 'film_type_master', 'region_master', 'part_master', 'make_master', 'macro_management', 'activity_logs', 'db_logs', 'file_upload', 'operation_logs', 'phone_extension', 'sequences'])) {
            return;
        }
    }
    if (strtolower($activity) == 'insert') {
        if (in_array($table, ['activity', 'activity_logs', 'db_logs', 'operation_logs'])) {
            return;
        }
    }
    $log = [
        'user_id' => session('admin.id'),
        'user_type' => session('admin.user_type'),
        'user_name' => session('admin.username') ?: session('admin.unique_id'),
        'ip' => request()->ip(),
        'method' => request()->method(),
        'url' => request()->url(),
        'operation' => $activity,
        'table_name' => $table,
        'query' => $query,
    ];
    Log::channel('ddd')->info(json_encode($log));
    return;
}
/*
 * 记录文件上传
 * file记录为文件地址，name记录为所属模块或来源
 * name：质保图片上传1、质保文件上传2、套餐图片上传3、卷号文件上传4
 * 改为数字，后期使用语言系统修改
 * type为public或store，1p2s，默认为p
 * */
function fLogs($file, $type = 1, $name = 1)
{
    if (session('admin.id')) {
        $user_id = session('admin.id');
    } else {
        $user = session()->get('admin');
        $user_id = @$user->id;
    }
    $log = new \App\Models\FileUpload();
    $log->user_id = $user_id;
    $log->type = (int) $type;
    $log->file = $file;
    $log->name = (int) $name;
    $log->save();
}

/*
 * rolls
 * */
function getResidueLengthByRollNumberAndGmsId($roll_number, $user_id)
{

    if (empty($roll_number) || empty($user_id)) {
        return ['status' => false, 'msg' => '参数为空！'];
    }
    /*$roll = $this->getRollsMasterByRollNumber($roll_number);
    $r_length = $this->getUserAssignResidueLengthByRollId($roll->id, $user_id);
    $used_length = getUserUsedLengthByRollNumber($roll_number, $user_id);*/
    return [
        'status' => 'SUCCESS',
    ];
}

function getRollsMasterByRollNumber($roll_number)
{
    // return RollMaster::where('roll_number', $roll_number)->first();
    return DB::table('roll_master')->where('roll_number', $roll_number)->first();
}

function getWarrantyUsedLengthById($id)
{
    $datas = DB::table('warranty_to_vehicle_coverage')
        ->where('warranty_id', $id)
        ->whereNull('deleted_at')
        ->get('length');
    return array_sum(Arr::pluck($datas, 'length'));
}
/*
 * 根据roll_number获取质保信息
 * 如果传入user_id，则获取传入用户ID提交的数据
 * 如果传入type=2，则获取传入用户及下属经销商的数据
 *
 * */
function getWarrantyRollsByRollNumber($roll_number, $user_id = 0, $type = 0)
{
    $model = DB::table('warranty_to_vehicle_coverage as wvc')
        ->where('roll_number', $roll_number)
        ->leftJoin('warranty as w', 'warranty.id', 'wvc.warranty_id')
        ->whereNull('wvc.deleted_at')
        ->whereNull('w.deleted_at');

    $select = ['wvc.roll_number', 'wvc.length', 'warranty.user_id', 'w.id', 'w.warranty_id', 'w.pre_id'];
    if ($user_id) {
        if ($type == 2) {
            $model = $model->whereIn('w.user_id', function ($query) use ($user_id) {
                $query->select('id')->from('users')
                    ->where('users.id', $user_id)
                    ->orWhere('creator_id', $user_id);
            });
        } else {
            $model = $model->where('w.user_id', $user_id);
        }
    }
    $model->select($select);
    return $model->get();
}
/*
 * 根据卷号获取质保信息使用的该卷号长度
 * 如果传入user_id，则获取该用户使用的长度
 * */
function getWarrantyUsedLengthByRollNumber($roll_number, $user_id = 0)
{
    $w = getWarrantyRollsByRollNumber($roll_number, $user_id);
    return array_sum(Arr::pluck($w, 'length'));
}
/*
 * 根据roll_number获取套餐信息
 * 如果传入user_id，则获取传入用户ID提交的数据
 * 如果传入type=2，则获取传入用户及下属经销商的数据
 * install=0为获取未安装数据，1则获取全部无论是否安装，2则仅获取已安装
 * */
function getPrecutRollsByRollNumber($roll_number, $user_id = 0, $type = 0, $install = 0)
{
    $model = DB::table('precut as p')
        ->leftJoin('precut_to_vehicle_coverage as pvc', 'pvc.precut_kit_sale_id', '=', 'p.id')
        ->where('roll_number', $roll_number)
        ->whereNull('p.deleted_at');
    if ($user_id) {
        if ($type == 2) {
            $model = $model->whereIn('p.user_id', function ($query) use ($user_id) {
                $query->select('id')->from('users')
                    ->where('users.id', $user_id)
                    ->orWhere('creator_id', $user_id);
            });
        } else {
            $model = $model->where('p.user_id', $user_id);
        }
    }

    if ($install == 1) {
    } elseif ($install == 2) {
        $model = $model->where('p.status', 1);
    } else {
        $model = $model->where('p.status', '!=', 1);
    }
    $model->select(['pvc.roll_number', 'pvc.length', 'p.user_id', 'p.created_by', 'p.user_id as sold_to_user_id', 'p.created_by as sold_by_user_id']);
    return $model->get();
}
function getPrecutUsedLengthByRollNumber($roll_number, $user_id = 0)
{
    $w = getPrecutRollsByRollNumber($roll_number, $user_id);
    return array_sum(Arr::pluck($w, 'length'));
}

function getUserUsedLengthByRollNumber($roll_number, $user_id = 0)
{
    $w = getWarrantyUsedLengthByRollNumber($roll_number, $user_id);
    $p = getPrecutUsedLengthByRollNumber($roll_number, $user_id);
    return $w + $p;
}

/*
 * 根据传入的多个卷号仅获取长度、卷号，
 * 返回的内容为卷号=》总长度
 * */
function getPrecutRollsLengthByRollNumbers($roll_numbers, $user_id = 0, $type = 0, $install = 0)
{
    $model = DB::table('precut as p')
        ->leftJoin('precut_to_vehicle_coverage as pvc', 'pvc.precut_kit_sale_id', '=', 'p.id')
        ->whereIn('roll_number', $roll_numbers)
        ->whereNull('p.deleted_at');
    if ($user_id) {
        // $model->where('ps.sold_to_user_id', $user_id);
    }
    if ($type == 2) {
        $model = $model->whereIn('p.user_id', function ($query) use ($user_id) {
            $query->select('id')->from('users')
                ->where('users.id', $user_id)
                ->orWhere('creator_id', $user_id);
        });
    } else if ($user_id) {
        $model = $model->where('ps.user_id', $user_id);
    }
    if ($install == 1) {
    } elseif ($install == 2) {
        $model = $model->where('p.status', 1);
    } else {
        $model = $model->where('p.status', '!=', 1);
    }
    $model->select(['pvc.roll_number', 'pvc.length']);
    $data = $model->get();
    return assocRollNumberAndTlength($data, $roll_numbers);
}

/*
 * 根据传入的多个卷号仅获取长度、卷号，
 * 返回的内容为卷号=》总长度
 * */
function getWarrantyRollsLengthByRollNumbers($roll_numbers, $user_id = 0, $type = 0, $install = 0)
{
    $model = DB::table('warranty_to_vehicle_coverage as wvc')
        ->whereIn('roll_number', $roll_numbers)
        ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
        ->whereNull('wvc.deleted_at')
        ->whereNull('w.deleted_at');
    if ($user_id) {
    }
    $select = ['wvc.roll_number', 'wvc.length'];
    if ($type == 2) {
        $model = $model->whereIn('w.user_id', function ($query) use ($user_id) {
            $query->select('id')->from('users')
                ->where('users.id', $user_id)
                ->orWhere('creator_id', $user_id);
        });
    } else if ($user_id) {
        $model = $model->where('w.user_id', $user_id);
    }
    $model->select($select);
    $data = $model->get();
    return assocRollNumberAndTlength($data, $roll_numbers);
}

function assocRollNumberAndTlength($data, $roll_numbers)
{
    $res = [];
    foreach ($data as $k => $v) {
        if (empty($res[$v->roll_number])) {
            $res[$v->roll_number] = $v->length;
        } else {
            $res[$v->roll_number] += $v->length;
        }
    }
    foreach ($roll_numbers as $k => $v) {
        $res[$v] = @$res[$v];
    }
    return $res;
}
/*
 * 根据分配表，获取用户剩余长度
 * */
function getUserAssignLengthByRollId($id, $user_id)
{
    $rolls = DB::table('roll_sales')->where('roll_id', $id)->get();
    $sold_to = 0; // 分配给用户的长度
    $sold_by = 0; // 用户分配出去的长度
    foreach ($rolls as $k => $v) {
        if ($v->sold_by_user_id == $user_id) {
            $sold_by -= $v->length;
        }
        if ($v->sold_to_user_id == $user_id) {
            $sold_to += $v->length;
        }
    }
    return $sold_to - $sold_by;
}
/*
 * 分配或被分配都记录，
 * 自己分配给自己仅需要记录一次
 * */
function getUserAssignByRollId($id, $user_id)
{
    $rolls = DB::table('roll_sales')->where('roll_id', $id)->get();
    $res = [];
    foreach ($rolls as $k => $v) {
        if ($v->sold_by_user_id == $user_id) {
            $res[] = $v;
        } else if ($v->sold_to_user_id == $user_id) {
            $res[] = $v;
        }
    }
    return $res;
}
/*
 * 获取分配表用户的剩余卷长度
 * 分配给自己也需要计算+-
 * 调货表仅记录待审核项，且仅记录调出，不记录调入
 * 成功调入项已存储在分配表
 * 如果是管理员，则增加长度，
 * 如果是管理员，且无分配记录，剩余长度为总长度
 * 如果已有分配记录，且剩余长度小于0，则增加长度，剩余长度不大于总长度
 * */
function getUserResidueAssignLengthByRollId($id, $user_id)
{
    $rolls = DB::table('roll_sales')->where('roll_id', $id)->get();
    $sold_to = 0; // 分配给用户的长度
    $sold_by = 0; // 用户分配出去的长度
    foreach ($rolls as $k => $v) {
        if ($v->sold_by_user_id == $user_id) {
            $sold_by += $v->length;
        }
        if ($v->sold_to_user_id == $user_id) {
            $sold_to += $v->length;
        }
    }
    $transfer = DB::table('roll_transfer')->where('roll_id', $id)->where('approved', 0)->get();
    foreach ($transfer as $k => $v) {
        if ($v->transfer_by_user_id == $user_id) {
            $sold_by += $v->length;
        }
    }
    $len = $sold_to - $sold_by;
    $user = Admin::findOrFail($user_id);
    $user_level = $user->user_type;
    if ($user_level == 1) {
        $roll = DB::table('roll_master')->find($id);
        if ($sold_by == 0) {
            $len += $roll->length;
        }
        if ($len < 0) {
            $len += $roll->length;
        }
    }
    return $len;
}
/*
 * 获取分配表用户的剩余卷长度
 * */
function getUserResidueAssignLengthByRollNumber($roll_number, $user_id)
{
    // $user_id = $user_id ?: session('admin.id');
    $roll = getRollsMasterByRollNumber($roll_number);
    return getUserResidueAssignLengthByRollId($roll->id, $user_id);
}
/*
 * 获取卷号用户分配记录
 * */
function getRollsUserAssignRecorderByRollId($id)
{
    return $rolls = DB::table('roll_sales')->where('roll_id', $id)->get();
}
/*
 * 获取卷号用户分配表及剩余长度
 * 先根据卷号查询所有分配记录，整理数据为user_id=>rlength
 * 然后获取所有质保、套件使用该卷号的记录，获取用户ID
 * */
function getRollsUserAssignResideuLengthByRollId($id)
{
    $roll = DB::table('roll_master')->find($id);
    $roll_sales = DB::table('roll_sales')->where('roll_id', $id)->get();
    $u1 = [];
    foreach ($roll_sales as $k => $v) {
        if (empty($u1[$v->sold_to_user_id])) {
            $u1[$v->sold_to_user_id] = 0;
        }
        if (empty($u1[$v->sold_by_user_id])) {
            $u1[$v->sold_by_user_id] = 0;
        }
        $u1[$v->sold_to_user_id] += $v->length;
        $u1[$v->sold_by_user_id] -= $v->length;
    }
    $w = getRollsUserUsedLengthInWarrantyByRollNumber($roll->roll_number);
    $p = getRollsUserUsedLengthInPrecutByRollNumber($roll->roll_number);
    $res = [];
    foreach ($u1 as $k => $v) {
        // $res[$k]
    }
}
/*
 * 质保信息，查询该卷号所有使用的记录
 * 返回数据格式为user_id=>tlength
 * */
function getRollsUserUsedLengthInWarrantyByRollNumber($roll_number)
{
    $w = DB::table('warranty_to_vehicle_coverage as wvc')
        ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
        ->where('wvc.roll_number', $roll_number)
        ->whereNull('wvc.deleted_at')
        ->whereNull('w.deleted_at')
        ->select('wvc.length', 'w.user_id')
        ->get();
    $res = [];
    foreach ($w as $k => $v) {
        if (empty($res[$v->user_id])) {
            $res[$v->user_id] = 0;
        }
        $res[$v->user_id] += $v->length;
    }
    return $res;
}
/*
 *
 * 套件新增时，自动将相关卷号赋值到分配表，type=3
 * 套件安装时，自动将卷号复制到质保表，质保主表设置套件ID
 * 查询套件使用长度时，仅计算sold_to_user_id的长度
 * 返回格式为user_id=>tlength
 * */
function getRollsUserUsedLengthInPrecutByRollNumber($roll_number)
{
    $w = DB::table('precut as p')
        ->leftJoin('precut_to_vehicle_coverage as pvc', 'pvc.precut_kit_sale_id', '=', 'p.id')
        ->where('roll_number', $roll_number)
        ->where('p.status', '!=', 1)
        ->whereNull('p.deleted_at')
        ->select('pvc.length', 'p.user_id')
        ->get();
    $res = [];
    foreach ($w as $k => $v) {
        if (empty($res[$v->user_id])) {
            $res[$v->user_id] = 0;
        }
        $res[$v->user_id] += $v->length;
    }
    return $res;
}

function getRollsUserAssignResideuLengthByRollNumber($id)
{
    $rolls = DB::table('roll_sales')->where('roll_id', $id)->get();
}
function getUserCanAssignLengthByRollId($id, $user_id)
{
    $x1 = getUserResidueAssignLengthByRollId($id, $user_id);
    $x2 = getUserUsedLengthByRollNumber($id, $user_id);
    return $x1 - $x2;
}

function getUserCanAssignLengthByRollNumber($roll_number, $user_id)
{
    $roll = getRollsMasterByRollNumber($roll_number);
    return getUserCanAssignLengthByRollId($roll->id, $user_id);
}

function getUserAssignResidueLengthByRollId() {}

/*
 * 检查质保提交数据是否正确
 * 发起审核时判断数据是否正确、管理员审核时判断数据是否正确
 * 是否判断经质保所属销商账号是否可用（非登录账号）？不判断
 * 仅判断是否有数据
 * */
function checkWarranty($id)
{
    $w = Warranty::findOrFail($id); // 获取质保
    $f = [
        'user_id' => '经销商',
        'first_name' => '顾客名称',
        'phone_number' => '手机号码',
        'email_address' => '邮箱',

        'region_id' => '地区',
        'province_id' => '省份',
        'city' => '城市',
        'address' => '地址',

        'year_id' => '年份',
        'make_id' => '品牌',
        'model_id' => '车型',
        'license_plate' => '车牌号',
        'vin_number' => '车架号',

        'installer_name' => '安装师傅',
        'installation_date' => '安装日期',
        'installation_price' => '安装价格',
        'image_front' => '车头图片',
        'image_back' => '车尾图片',
        'image_driver_side' => '正驾驶侧图片',
        'image_passenger_side' => '副驾驶侧图片',
    ];
    foreach ($f as $k => $v) {
        $kk = trim($w->$k);
        if (empty($kk)) {
            return ['status' => false, 'msg' => $v . ' 不能为空！'];
        }
    }
    if (empty($w->warranty_id)) {
        $w->warranty_id = makeWarrantyId($w->installation_date);
        $w->save(); // 需要保存数据
    }
    if (empty($w->pre_id)) {
        $wv = DB::table('warranty_to_vehicle_coverage')
            ->where('warranty_id', $w->id)
            ->whereNull('deleted_at')
            ->get(['part_id', 'length', 'roll_number']); // 获取卷号
        return checkPartItems($wv);
    }
    return ['status' => 'SUCCESS'];
}
function checkWarrantyOld($id)
{
    $w = Warranty::findOrFail($id); // 获取质保
    $wv = DB::table('warranty_to_vehicle_coverage')
        ->where('warranty_id', $w->id)
        ->whereNull('deleted_at')
        ->get(['part_id', 'length', 'roll_number']); // 获取卷号
    $p = DB::table('part_master')->whereIn('id', Arr::pluck($wv, 'part_id'))->get(['id', 'min_length']); // 获取部位
    $f = [
        'user_id' => '经销商',
        'first_name' => '顾客名称',
        'phone_number' => '手机号码',
        'email_address' => '邮箱',

        'region_id' => '地区',
        'province_id' => '省份',
        'city' => '城市',
        'address' => '地址',

        'year_id' => '年份',
        'make_id' => '品牌',
        'model_id' => '车型',
        'license_plate' => '车牌号',
        'vin_number' => '车架号',

        'installer_name' => '安装师傅',
        'installation_date' => '安装日期',
        'installation_price' => '安装价格',
        'image_front' => '车头图片',
        'image_back' => '车尾图片',
        'image_driver_side' => '正驾驶侧图片',
        'image_passenger_side' => '副驾驶侧图片',
    ];
    foreach ($f as $k => $v) {
        $kk = trim($w->$k);
        if (empty($kk)) {
            return ['status' => false, 'msg' => $v . ' 不能为空！'];
        }
    }
    if (empty($w->warranty_id)) {
        $w->warranty_id = makeWarrantyId($w->installation_date);
        $w->save(); // 需要保存数据
    }
    // 根据部位判断最小长度是否符合要求
    $pl = [];
    foreach ($p as $k => $v) {
        $pl[$v->id] = $v->min_length;
    }
    $wvt = []; // 总长度
    $rlt = []; // 卷号总长度
    $rns = Arr::pluck($wv, 'roll_number');
    if (count($wv) < 1) {
        return ['status' => false, 'msg' => '装贴部位不能为空！'];
    }
    foreach ($wv as $k => $v) {
        if ($v->length < $pl[$v->part_id]) {
            return ['status' => false, 'msg' => ts('part_master.' . $v->part_id) . ' 最小长度不符合要求！'];
        }
        if (empty($v->roll_number)) {
            return ['status' => false, 'msg' => '卷号不能为空！'];
        }
        $wvt[$v->part_id] = @$wvt[$v->part_id] + $v->length;
        $rlt[$v->roll_number] = @$rlt[$v->roll_number] + $v->length;
    }
    // 假如部位是全车或小车，判断总长度是否满足
    if (isset($wvt[18]) && $wvt[18] < 1000) {
        return ['status' => false, 'msg' => ts('part_master.18') . ' 最小长度不符合要求！'];
    }
    if (isset($wvt[40]) && $wvt[40] < 850) {
        return ['status' => false, 'msg' => ts('part_master.40') . ' 最小长度不符合要求！'];
    }
    // 判断用户是否有足够的卷长度
    foreach ($rlt as $k => $v) {
    }
    return ['statue' => 'SUCCESS', 'status' => 'SUCCESS'];
}
/*
 * 获取用户可以用来
 * */
function getURCL($roll_number, $user_id) {}

/*function checkPartMinLength() {


}*/
/*
 * 仅判断最小长度，不判断卷号是否归属用户
 * */
function checkPartMinLength($datas)
{
    $pids = Arr::pluck('part_id');
    $rs = Arr::pluck('roll_number');
}
function checkUserRollLength($roll_number, $user_id) {}

function getLoginId()
{
    if (session('admin.id')) {
        $user_id = session('admin.id');
    } else {
        $user = session()->get('admin');
        $user_id = @$user->id;
    }
    return $user_id;
}
function getLoginUser()
{
    if (session('admin.id')) {
        $user_id = session('admin.id');
    } else {
        $user = session()->get('admin');
        $user_id = @$user->id;
    }
    return Admin::findOrFail($user_id);
}
/*
 * 严格模式
 * 判断传入的user_id是不是当前登录用户或下属经销商
 * 当传入用户为盛大时，登录用户必须为本人
 * 当登录用户为管理员时，必须为下属经销商
 * 当传入用户为管理员时，返回false*/
function checkDBSs($user_id)
{
    $user_id = (int) $user_id;
    $admin_id = session('admin.id');
    if (empty($user_id)) {
        return false;
    }
    $user = getLoginUser();
    if ($user->user_type == 3) {
        return false;
    }
    $u = Admin::withTrashed()->findOrFail($user_id);
    if ($u->user_type == 2 && $user_id != $admin_id) {
        return false;
    }
    if ($u->user_type == 1) {
        return false;
    }
    if ($u->creator_id == $user->id || $u->id == $user->id) {
        return true;
    }
    return false;
}
/*
 * 判断user_id是不是当前登录用户或下属经销商
 * 如果是管理员，则允许全部
 * 如果user_id为空，返回true
 * 返回true,false
 * */
function checkDealerBelongs($user_id)
{
    $user_id = (int) $user_id;
    if (empty($user_id)) {
        return true;
    }
    $user = getLoginUser();
    if ($user->user_type == 1) {
        return true;
    }
    $u = Admin::withTrashed()->findOrFail($user_id);
    if ($u->creator_id == $user->id || $u->id == $user->id) {
        return true;
    }
    return false;
}

/*
 * 根据日期生成质保ID，并去掉重复数据
 * ymd+4位随机数
 * */
function makeWarrantyId($date = null)
{
    if (empty($date)) {
        $date = date('ymd');
    } else {
        $t = strtotime($date);
        if ($t <= strtotime('2000-01-01')) {
            $t = time();
        }
        $date = date('ymd', $t);
    }
    $ws = DB::table('warranty')->where('warranty_id', 'like', $date . '%')->get('warranty_id');
    $wid = Arr::pluck($ws, 'warranty_id');
    $a1 = [];
    foreach (range(0, 9999) as $v) {
        $a1[] = $date . str_pad($v, 4, '0', STR_PAD_LEFT);
    }
    $a1 = array_unique($a1);
    $a2 = array_diff($a1, $wid);
    if (empty($a2)) {
        foreach (range(1, 2) as $k) {
            foreach (range(0, 9999) as $v) {
                $a2[] = ($date + 31 * $k) . str_pad($v, 4, '0', STR_PAD_LEFT);
            }
        }
        foreach (range(1, 7) as $k) {
            $date = $date + 1200 * $k;
            foreach (range(0, 2) as $d) {
                foreach (range(0, 9999) as $v) {
                    $a2[] = ($date + 31 * $d) . str_pad($v, 4, '0', STR_PAD_LEFT);
                }
            }
        }
        $a2 = array_unique($a2);
        $a2 = array_diff($a2, $wid);
    }
    $r = array_rand($a2);
    return $a2[$r];
}


function verifyWarranty() {}


// v1.1
/*
 * 根据卷号、用户ID获取用户剩余长度
 * 可用于可分配、可调货、可新增长度
 * V1.2已重做
 * */
function getRestLenV101($roll_number, $user_id)
{
    $roll = getRollsMasterByRollNumber($roll_number);
    $user = Admin::findOrFail($user_id);
    if (empty($roll->id)) {
        return 0;
    }
    $user_level = $user->user_type;
    $asl = getUserResidueAssignLengthByRollId($roll->id, $user_id);
    $wt = getWTLen($roll_number, $user_id);
    $pt = getPSTLen($roll_number, $user_id);
    $len = $asl - $wt - $pt;
    return $len;
}
/*
 * 质保（非套件安装）使用长度*/
function getWTLen($roll_number, $user_id)
{
    $w = getWarrantyRollsByRollNumber($roll_number, $user_id);
    $len = 0;
    foreach ($w as $k => $v) {
        if (empty($v->pre_id)) {
            $len += $v->length;
        }
    }
    return $len;
}
/*
 * 获取套件出售卷号记录总长度*/
function getPSTLen($roll_number, $user_id)
{
    $w = getPrecutRollsByRollNumber($roll_number, $user_id);
    $len = 0;
    foreach ($w as $k => $v) {
        if ($v->sold_by_user_id == $user_id) {
            $len += $v->length;
        }
    }
    return $len;
}

/*
 * 根据质保ID获取卷号使用记录*/
function getWTLenByRN($id, $roll_number = 0)
{
    $w = getWVCByID($id);
    $len = 0;
    if ($roll_number) {
        foreach ($w as $k => $v) {
            if ($v->roll_number == $roll_number) {
                $len += $v->length;
            }
        }
    } else {
        foreach ($w as $k => $v) {
            $len += $v->length;
        }
    }
    return $len;
}

/*
 * 根据套餐ID获取卷号使用长度*/
function getPSTLenByRN($id, $roll_number = 0)
{
    $w = getPVCByID($id);
    $len = 0;
    if ($roll_number) {
        foreach ($w as $k => $v) {
            if ($v->roll_number == $roll_number) {
                $len += $v->length;
            }
        }
    } else {
        foreach ($w as $k => $v) {
            $len += $v->length;
        }
    }
    return $len;
}

/*
 * 根据质保ID获取装贴部位记录*/
function getWVCByID($id)
{
    $id = (int) $id;
    $w = DB::table('warranty_to_vehicle_coverage')
        ->where('warranty_id', $id)
        ->whereNull('deleted_at')
        ->whereNotNull('warranty_id')
        ->where('warranty_id', '!=', 0)
        ->get(['roll_number', 'length', 'part_id', 'precut_or_manual', 'film_type_id']);
    return $w;
}
/*
 * 根据套餐ID获取装贴部位记录*/
function getPVCByID($id)
{
    $w = DB::table('precut_to_vehicle_coverage as pvc')
        // ->leftJoin('precut as p', 'p.id', '=', 'pvc.precut_kit_sale_id')
        ->where('precut_kit_sale_id', $id)
        ->get(['pvc.roll_number', 'pvc.length']);
    return $w;
}
/*
 * 根据卷号获取质保使用记录*/
function getRWVC($rn) {}
/*
 * 获取用户*/
function getUsers($type, $creator_id)
{
    $w = DB::table('users');
    if ($type == 2) {
        $w = $w->where('user_type', 2);
    } elseif ($type == 3) {
        $w = $w->where('user_type', 3);
        if ($creator_id) {
            $w = $w->where('creator_id', $creator_id);
        }
    }
    $w = $w->where('status', 1)
        ->whereNull('deleted_at')
        ->get();
    return $w;
}
/*
 * 获取用户*/
function getUser($id)
{
    return Admin::withTrashed()->find($id);
}
/*
 * 获取用户简称或公司名称*/
function getJc($id)
{
    $u = getUser($id);
    if (empty($u) || empty($u->id)) {
        return false;
    }
    return $u->abbr ?: $u->companyt_name;
}
/*
 * 根据用户ID，获取省代简称*/
function getDJc($id)
{
    $u = getUser($id);
    if (empty($u) || empty($u->id)) {
        return false;
    }
    if ($u->user_type != 3) {
        return $u->abbr ?: $u->companyt_name;
    }
    $d = getUser($u->creator_id);
    if (empty($d) || empty($d->id)) {
        return false;
    }
    return $d->abbr ?: $d->companyt_name;
}
/*
 * 获取省代*/
function getDistributors()
{
    /*$w = DB::table('users')
        ->where('user_type', 2)
        ->where('status', 1)
        ->get();*/
    $w = Admin::where('user_type', 2)
        ->where('status', 1)
        ->get();
    return $w;
}
/*
 * 获取经销商*/
function getDealers($creator_id = null)
{
    /*$w = DB::table('users')
        ->where('user_type', 3)
        ->where('status', 1);*/
    $w = Admin::where('user_type', 3)
        ->where('status', 1)
        ->orderBy('status')
        ->orderByRaw(DB::raw('FIELD(mdtype, 1,3,4,2)'))
        ->orderBy('unique_id');
    if ($creator_id) {
        $w = $w->where('creator_id', $creator_id);
    }
    $w = $w->get();
    return $w;
}
/*
 * 获取省代自己及下属经销商*/
function getDDs($creator_id,$warranty_self=0)
{
    /*$w = DB::table('users')
        ->where(function ($query) use ($creator_id) {
            $query->where('id', $creator_id)
                ->orWhere('creator_id', $creator_id);
        })
        ->where('status', 1);*/
    $w = Admin::where(function ($query) use ($creator_id,$warranty_self) {
        if($warranty_self==1){
            $query->Where('creator_id', $creator_id);
        }else{
            $query->where('id', $creator_id)
                ->orWhere('creator_id', $creator_id);
        }
    })
        ->where('status', 1);
    $w = $w->orderBy('user_type')->orderByDesc('id')->get();
    return $w;
}

function getDistributions(int $userId)
{
    return DB::table('users')->leftJoin('users_relation', 'users_relation.belong_user_id', 'users.id')
        ->where('users_relation.user_id', $userId)
        ->where('users.status', 1)
        ->select('users.*')
        ->orderBy('id')->get();
}

/*
 * 仅判断最小长度，不判断卷号是否归属用户
 * */
function checkPartLen($data)
{
    $len = (int) $data['length'];
    if (empty($len)) {
        return false;
    }
    $part = DB::table('part_master')->find($data['part_id']);
    if (empty($part->id)) {
        return false;
    }
    if ($len < $part->min_length) {
        return false;
    }
    return true;
}
/*
 * 小车与全车单独判断*/
function checkPartsLen($datas)
{
    $pl = [];
    $wvt = $rlt = [];
    foreach ($datas as $k => $v) {
        $wvt[$v['part_id']] = @$wvt[$v['part_id']] + $v['length'];
        $rlt[$v['roll_number']] = @$rlt[$v['roll_number']] + $v['length'];
    }
    // 假如部位是全车或小车，判断总长度是否满足
    if (isset($wvt[18]) && $wvt[18] < 1000) {
        return ['status' => false, 'msg' => ts('part_master.18') . ' 最小长度不符合要求！'];
    }
    if (isset($wvt[40]) && $wvt[40] < 850) {
        return ['status' => false, 'msg' => ts('part_master.40') . ' 最小长度不符合要求！'];
    }
}
/*
 * 判断卷号*/
function checkPartItem($item, $user_id)
{
    $roll = getRollsMasterByRollNumber($item['roll_number']);
    if (empty($roll->id)) {
        return false;
    }
    if (empty($item['part_id'])) {
        return false;
    }

    return [
        'status' => 'SUCCESS',
        'data' => [
            'roll_number' => $roll->roll_number,
            'part_id' => $item['part_id'],
            'length' => $item['length'],
            'width' => $roll->width,
            'film_type_id' => $roll->film_type_id,
        ]
    ];
}
/*
 * 根据链接地址获质保或者套餐使用的数据
 * 仅在内部提交中使用，所以获取的是当前路径*/
function getModelCoverages()
{
    $method = request()->method();
    $path = request()->path();
    $refer = request()->header('referer');
    $id = 0;
    $t = '';
    $c = [];
    if ($path == 'admin/precut' || $path == 'admin/precut/') {
        $t = 'precut';
        $id = 0;
    } elseif ($path == 'admin/warranty' || $path == 'admin/warranty/') {
        $t = 'warranty';
        $id = 0;
    } elseif (stripos($path, 'admin/precut/') === 0) {
        $t = 'precut';
        $id = str_replace('admin/precut/', '', $path);
    } elseif (stripos($path, 'admin/warranty/') === 0) {
        $t = 'warranty';
        $id = str_replace('admin/warranty/', '', $path);
    }
    $id = (int) $id;
    if ($id) {
        if ($t == 'precut') {
            $c = DB::table('precut_to_vehicle_coverage')
                ->whereNull('deleted_at')
                ->where('precut_kit_sale_id', $id)
                ->get(['roll_number', 'length']);
        } elseif ($t == 'warranty') {
            $c = DB::table('warranty_to_vehicle_coverage')
                ->whereNull('deleted_at')
                ->where('warranty_id', $id)
                ->get(['roll_number', 'length']);
        }
    }
    return $c;
}

/*
 * 整理装贴部位提交数据，
 * 如果没有传入用户id，则使用提交的ID*/
function cmics($user_id = null)
{
    $user_id = $user_id ?: (int) request()->input('user_id');
    $part = request()->input('part');
    $roll_number = request()->input('roll_number');
    $length = request()->input('length');
    $width = request()->input('width');
    $film_type_id = request()->input('film_type_id') ?: [];
    $precut_or_manual = request()->input('precut_or_manual') ?: [];
    $wups = [];
    foreach ($part as $k => $v) {
        $wups[] = [
            'part_id' => $v,
            'roll_number' => @$roll_number[$k],
            'length' => @$length[$k],
            'width' => @$width[$k],
            'film_type_id' => @$film_type_id[$k],
            'precut_or_manual' => @$precut_or_manual[$k],
        ];
    }
    $udts = checkPartItems($wups, $user_id);
    return $udts;
}
/*
 * 质保时不判断套餐数据，
 * 套餐数据增改时判断
 * 多项数据判断
 * 判断装贴部位*/
function checkPartItems($items, $user_id = null, $type = 'warranty', $id = null)
{
    $admin_id = session('admin.id');
    $admin_type = session('admin.user_type');
    if (empty($user_id)) {
        if ($admin_type == 1) {
            $user_id = 1;
        } else {
            $user_id = $admin_id;
        }
    }
    $items = (array) $items;
    $status = 'SUCCESS';
    $datas = [];
    $rns = Arr::pluck($items, 'roll_number'); // 卷号可能有重复
    $pts = Arr::pluck($items, 'part_id');
    $rolls = DB::table('roll_master')->whereIn('roll_number', $rns)->get(['id', 'roll_number', 'width', 'film_type_id']); // 所有卷号
    $parts = DB::table('part_master')->whereIn('id', $pts)->get(['id', 'min_length']);
    if (count($rolls) < 1) {
        return fs2("膜卷号不存在");
    }
    if (count($parts) < 1) {
        return fs2("装贴部位不存在");
    }
    $ras = $pms = $rrs = []; // 各卷号剩余长度
    foreach ($rolls as $k => $v) {
        $rrs[$v->roll_number] = getRestLen($v->roll_number, $user_id);
        $ras[$v->roll_number] = $v;
    }
    $cs = getModelCoverages();
    foreach ($cs as $k => $v) {
        if (empty($rrs[$v->roll_number])) {
            $rrs[$v->roll_number] = $v->length;
        } else {
            $rrs[$v->roll_number] += $v->length;
        }
    }

    foreach ($parts as $k => $v) {
        $pms[$v->id] = $v->min_length; // 部位最小长度
    }
    $pis = $ris = [];
    foreach ($items as $k => $v) {
        if (!isset($pms[$v['part_id']])) {
            return fs2("装贴部位 " . $v['part_id'] . " 不存在");
        }
        if (empty($ras[$v['roll_number']])) {
            return fs2($v['roll_number'] . ' 卷号不存在！');
        }
        if ($v['length'] < @$pms[$v['part_id']]) {
            return fs2(ts('part_master.' . $v['part_id']) . ' 最小长度不符合要求！');
        }
        $pis[$v['part_id']] = @$pis[$v['part_id']] + $v['length'];
        $ris[$v['roll_number']] = @$ris[$v['roll_number']] + $v['length'];
        $r = $ras[$v['roll_number']];
        $datas[] = [
            'roll_number' => @$v['roll_number'],
            'part_id' => @$v['part_id'],
            'length' => @$v['length'],
            'width' => $r->width,
            'film_type_id' => $r->film_type_id,
            'precut_or_manual' => @$v['precut_or_manual'],
        ];
    }
    /*小车与全车判断总长度*/
    if (isset($pis[18]) && $pis[18] < 1000) {
        return fs2(ts('part_master.18') . ' 最小长度不符合要求！');
    }
    if (isset($pis[40]) && $pis[40] < 850) {
        return fs2(ts('part_master.40') . ' 最小长度不符合要求！');
    }
    foreach ($ris as $k => $l) {
        if ($l > $rrs[$k]) {
            return fs2($k . ' 渠道该卷号剩余长度不足！' . $rrs[$k]);
        }
    }
    return fs1($datas);
}

function fs1($data)
{
    return [
        'status' => 'SUCCESS',
        'data' => $data
    ];
}
function fs2($msg)
{
    return [
        'status' => false,
        'msg' => $msg
    ];
}


/*
 * 200
 * OK
 * 请求成功 */
function fs200($msg = '成功', ...$arg)
{
    return response()->json(['status' => 'SUCCESS', 'msg' => $msg, $arg], 200);
}

/*
 * 400
 * 语义有误
 * 请求参数有误*/
function fs400($msg, ...$arg)
{
    return response()->json(['status' => false, 'msg' => $msg, $arg], 400);
}
/*
 * 403
 * 禁止访问*/
function fs403($msg = '禁止访问', ...$arg)
{
    return response()->json(['status' => false, 'msg' => $msg, $arg], 403);
}
/*
 * 404
 * 没有找到*/
function fs404($msg = '没有找到', ...$arg)
{
    return response()->json(['status' => false, 'msg' => $msg, $arg], 404);
}

/*
 * 405
 * 请求方法不正确*/
function fs405($msg, ...$arg)
{
    return response()->json(['status' => false, 'msg' => $msg, $arg], 405);
}

/*
 * 500
 * 请求方法不正确*/
function fs500($msg, ...$arg)
{
    return response()->json(['status' => false, 'msg' => $msg, $arg], 500);
}

/*
 * 200
 * OK
 * 请求成功 */
function fs200d($msg = '成功', $data = [], ...$arg)
{
    return response()->json(['status' => 'SUCCESS', 'msg' => $msg, 'data' => $data, $arg], 200);
}

function rs1($content, $url = null)
{
    if ($url) {
        return redirect($url)->with('trash', $content);
    } else {
        return redirect()->back()->with('trash', $content);
    }
}
function rs2($content, $url = null)
{
    if ($url) {
        return redirect($url)->with('trash', ['content' => $content, 'type' => 'error']);
    } else {
        return redirect()->back()->with('trash', ['content' => $content, 'type' => 'error']);
    }
}
function rs3($content, $url = null)
{
    if ($url) {
        return redirect($url)->withInput()->with('trash', $content);
    } else {
        return redirect()->back()->withInput()->with('trash', $content);
    }
}
function rs4($content, $url = null)
{
    if ($url) {
        return redirect($url)->withInput()->with('trash', ['content' => $content, 'type' => 'error']);
    } else {
        return redirect()->back()->withInput()->with('trash', ['content' => $content, 'type' => 'error']);
    }
}
/*function toArray($orm)
{
    return array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $orm->items);
}*/
/*
 * v1.2*/
/*
 * 增加剩余长度*/
function plusRestlen($user_id, $roll_number, $len)
{
    $user_id = (int)$user_id ?: 1;
    if (empty($roll_number) || empty($len)) {
        return false;
    }
    $roll = RollMaster::withTrashed()->where('roll_number', $roll_number)->first();
    $s2 = RollRestlen::firstOrNew([
        'user_id' => $user_id,
        'roll_number' => $roll_number
    ]);
    $s2->user_id = $user_id;
    $s2->roll_number = $roll_number;
    $length = $s2->restlen + $len;
    if ($length <= @$roll->length) {
        $s2->restlen = $s2->restlen + $len;
    } else {
        $s2->restlen = @$roll->length;
    }
    /*$s2->restlen = $s2->restlen + $len;
    if ($s2->restlen > @$roll->length) {
        return false;
    }*/
    $s2->save();
    return $s2;
}

/*
 * 减少剩余长度*/
function minusRestlen($user_id, $roll_number, $len)
{
    $s2 = RollRestlen::firstOrNew([
        'user_id' => $user_id,
        'roll_number' => $roll_number
    ]);
    $s2->restlen = $s2->restlen - $len;
    $s2->save();
    if ($s2->restlen < 0) {
        return false;
    }
    return $s2;
}
/*
 * 初始化长度*/
function initRestlen($user_id, $roll_number, $len)
{
    $user_id = (int)$user_id ?: 1;
    if (empty($roll_number) || empty($len)) {
        return;
    }
    $roll = RollMaster::withTrashed()->where('roll_number', $roll_number)->first();
    $s2 = RollRestlen::withTrashed()->firstOrNew([
        'user_id' => $user_id,
        'roll_number' => $roll_number
    ]);
    $s2->user_id = $user_id;
    $s2->roll_number = $roll_number;
    $s2->restlen = $roll->length;
    $s2->save();
    return $s2;
}
/*
 * 卷号分配*/

/*
 * 单质保
 * 删除质保时恢复剩余长度
 * 涉及到单用户多卷号*/
function editRestlenW($warranty_id)
{
    $data = DB::table('warranty_to_vehicle_coverage as wvc')
        ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
        ->where('wvc.warranty_id', $warranty_id)
        ->whereNull('wvc.deleted_at')
        ->select(['wvc.*', 'w.user_id', 'w.pre_id'])
        ->get();
    foreach ($data as $k => $v) {
    }
}

function editRestlen($user_id, $roll_number, $len, $type = 1)
{
    $s2 = RollRestlen::firstOrNew([
        'user_id' => $user_id,
        'roll_number' => $roll_number
    ]);
    if ($type == 1) {
        $s2->restlen = $s2->restlen + $len;
    } else {
        $s2->restlen = $s2->restlen - $len;
    }
    $s2->save();
}

function addRollSales($roll_id, $sold_by_user_id, $sold_to_user_id, $length, $type = 1)
{
    $sales = new RollSales();
    $sales->roll_id = $roll_id;
    $sales->sold_by_user_id = $sold_by_user_id;
    $sales->sold_to_user_id = $sold_to_user_id;
    $sales->is_precut = 0;
    $sales->length = $length;
    $sales->date_sold = date('Y-m-d H:i:s');
    $sales->created_by = session('admin.id');
    $sales->type = $type;
    $sales->save();
    alogs('膜卷', '分配', $roll_id, $sales, null);
    return $sales->id;
}

function addRollTransfer($roll_id, $transfer_by_user_id, $transfer_to_user_id, $length, $note)
{
    $model = new RollTransfer();
    $model->roll_id = $roll_id;
    $model->transfer_by_user_id = $transfer_by_user_id;
    $model->transfer_to_user_id = $transfer_to_user_id;
    $model->length = $length;
    $model->note = $note;
    $model->approved = 0;
    $model->created_by = session('admin.id');
    $model->save();
    alogs('调货', '发起', $roll_id, $model, null);
    return $model;
}
/*
 * 更新用户状态*/
function editUserStatus($user, $status = 0)
{
    $model = new UserAssist();
    $model->user_id = $user->id;
    if ($status) {
        $model->status = $status;
    } else {
        $model->status = $user->status;
        $status = $user->status;
    }
    $note = request()->input('note');
    $note = trim($note);
    $model->note = substr($note, 0, 255);
    $model->created_by = session('admin.id');
    $model->save();
    if ($status == 1) {
        $name = '启用';
    } elseif ($status == 3) {
        $name = '重置密码';
    } elseif ($status == 4) {
        $name = '删除';
    } else {
        $name = '停用';
    }
    if ($user->user_type == 1) {
        $module = '管理员';
    } else if ($user->user_type == 2) {
        $module = '省代';
    } else {
        $module = '经销商';
    }
    alogs($module, $name, $user->id, $model, null);
}

/*
 * 获取用户历史变更记录*/
function getUSH($user_id)
{
    $datas = DB::table('users_r1 as ur')
        ->leftJoin('users as u', 'u.id', 'ur.created_by')
        ->where('ur.user_id', $user_id)
        ->orderByDesc('ur.id')
        ->get(['ur.id', 'ur.status', 'u.abbr', 'ur.created_at', 'ur.created_by', 'ur.note']);
    return $datas;
}
/*
 * 根据套餐ID获取用户ID（sold_by_user_id)
 * 删除质保、删除套餐或更新套餐时，需要获取用户ID来更新剩余长度
 * */
function getPreUid($pre_id)
{
    $pmod = DB::table('precut as p')
        ->where('p.id', $pre_id)
        ->first();
    if (empty($pmod)) {
        $user_id = 1;
    } else {
        $user_id = $pmod->created_by;
    }
    $user_id = $user_id ?: 1;
    return $user_id;
}
/*
 * 根据主键ID获取套餐ID*/
function getPPId($id)
{
    $model = DB::table('precut')->find($id);
    return @$model->precut_id;
}
/*
 * 根据套餐ID获取主键ID*/
function getPIdP($precut_id)
{
    $model = DB::table('precut')->where('precut_id', $precut_id)->first();
    return @$model->id;
}

/*
 * 删除质保
 * 根据ID删除
 * 管理员可以删除全部
 * 非管理员仅可以删除归属于自己，且状态为待提交或审核被拒绝的数据
 * 所有删除为软删除*/
function deleteWarranty($id)
{
    $user_id = session()->get('admin.id');
    $user_type = session()->get('admin.user_type');
    $model = Warranty::find($id);
    if (empty($model->id)) {
        return fs404('质保信息不存在！');
    }
    if ($user_type == 2) {
        if (empty($model->user_id)) {
            if ($model->created_by != $user_id) {
                return fs403('无权限操作该数据！');
            }
        } else {
            if (!checkDealerBelongs($model->user_id)) {
                return fs403('无权限操作该数据！');
            }
        }
        if (!in_array($model->approved, [2, 3])) {
            return fs403('已提交数据 无权限删除！');
        }
    }

    /*if ($user_type == 1) {
        $model = Warranty::where('id', $id);
    } else {
        $model = Warranty::where('id', $id)
            ->whereIn('user_id', function ($query) use ($user_id) {
                $query->select('id')->from('users')
                    ->where('users.id', $user_id)
                    ->orWhere('creator_id', $user_id);
            })
            ->whereIn('approved', [2, 3]);
    }
    $data = $model->first();*/
    DB::beginTransaction();
    try {
        if (!empty($model->id)) {
            $w = DB::table('warranty_to_vehicle_coverage')
                ->whereNull('deleted_at')
                ->where('warranty_id', $id);
            $wdata = DB::table('warranty_to_vehicle_coverage')
                ->whereNull('deleted_at')
                ->where('warranty_id', $id)
                ->get();
            if (empty($model->pre_id) && empty($model->precut_id)) {
                if (!empty($wdata) && in_array($model->approved, [0, 1, 2])) {
                    foreach ($wdata as $k => $v) {
                        $e = plusRestlen($model->user_id, $v->roll_number, $v->length);
                        if (empty($e)) {
                            DB::rollback(); //数据库回滚
                            return fs500('服务器错误，删除失败3！' . $e, [$model->user_id, $v->roll_number, $v->length, $e]);
                        }
                    }
                }
            }
            if ($model->pre_id) {
                $p = Precut::find($model->pre_id);
                if (!empty($p->id)) {
                    $p->status = 0;
                    $p->save();
                }
            }
            alogs('质保', '删除', $model->id, $new = null, mmc($model, $wdata));
            Warranty::where('id', $id)->update([
                'deleted' => 1,
            ]);
            $bool = $model->delete();
            /* 修改配件状态*/
            if ($model->precut_id) {
                $precut = NewPrecut::find($model->precut_id);
                if (!empty($precut->id)) {
                    $precut->status = 0;
                    $precut->save();
                }
            }
            $e = WarrantyToVehicleCoverage::where('warranty_id', $model->id)->delete();
            /*if (empty($e)) {
                DB::rollback();//数据库回滚
                return fs500('服务器错误，删除失败1！');
            }*/

            DB::commit();
            return fs200('删除成功！');
        }
    } catch (\Exception $exception) {
        DB::rollback(); //数据库回滚
        return fs500('服务器错误，删除失败！');
    }

    return fs404('没有找到质保信息！');
}

/*
 * 删除套餐
 * 根据ID删除
 * 仅管理员可以删除
 * */
function deletePrecut($id)
{
    $user_id = session()->get('admin.id');
    $user_type = session()->get('admin.user_type');
    if ($user_type != 1 && !checkAuthority()) {
        abort(403);
    }
    // $m = DB::table('precut')->where('id', $id);
    $m = Precut::where('id', $id);
    $data = $m->first();
    if (empty($data)) {
        abort(404);
    }
    if ($data->status == 1) {
        return ['status' => false, 'msg' => '已安装套餐无法删除'];
    }
    $c = DB::table('precut_to_vehicle_coverage')->where('precut_kit_sale_id', $id);
    $cs = $c->get();
    foreach ($cs as $k => $v) {
        plusRestlen($data->created_by, $v->roll_number, $v->length);
    }
    $data->coverages = $cs;
    $ws = DB::table('warranty')->where('pre_id', $id)->get();
    $ids = Arr::pluck($ws, 'id');
    foreach ($ids as $k => $v) {
        deleteWarranty($v);
    }
    $alogs = alogs('套餐', '删除', $data->id, null, mpmc($data, $cs, $ws));
    $bool = $m->delete();
    return ['status' => 'SUCCESS', 'msg' => '成功！'];
}

/*
 * 删除卷号
 * 根据ID删除
 * 如果质保、或套餐中使用了改卷号，需要先删除信息，然后再删除卷号
 * 仅管理员可以删除*/
function deleteRoll($id)
{
    $user_id = session()->get('admin.id');
    $user_type = session()->get('admin.user_type');
    /*if ($user_type != 1) {
        abort(404);
    }*/
    checkMethodsAuthority('roll_delete');
    checkAuthority();
    $model = RollMaster::findOrFail($id);
    if (!empty($model->status)) {
        return ['status' => false, 'msg' => '膜已被分配，无法删除'];
    }
    /*
    $w = DB::table('warranty_to_vehicle_coverage as wvc')
        ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
        ->where('wvc.roll_number', $model->roll_number)
        ->whereNull('w.deleted_at')
        ->get();
    if (count($w)) {
        return ['status' => false, 'msg' => '质保系统已使用该卷号，请先删除质保，再删除卷号', 'data'=>$w];
    }
    $p = DB::table('precut as p')
        ->leftJoin('precut_to_vehicle_coverage as pvc', 'pvc.precut_kit_sale_id', 'p.id')
        ->where('roll_number', $model->roll_number)
        ->whereNull('p.deleted_at')
        // ->where('p.status', '!=', 1)
        ->select('pvc.roll_number', 'pvc.length', 'p.created_by')
        ->get();
    if (count($p)) {
        return ['status' => false, 'msg' => '专享套餐中有使用该卷号，请先删除，再删除卷号', 'data'=>$w];
    }
    $s = RollSales::where('roll_id',$model->id)->count('id');
    if ($s) {
        return ['status' => false, 'msg' => '已分配卷号无法删除！', 'data'=>$w];
    }
    */
    RollMaster::where('id', $id)->update([
        'deleted' => 1,
    ]);
    $bool = $model->delete();
    $alogs = alogs('膜卷', '删除', $model->id, null, $model);
    return ['status' => 'SUCCESS', 'msg' => '成功！'];
}
/*
 * 删除经销商
 * 根据ID删除经销商
 * 同时删除经销商所属质保信息=>不删除质保信息
 * 不删除套餐信息
 * 删除已分配卷号、恢复已分配卷号长度？
 * 删除剩余长度、不删除分配记录
 * 新增分配记录，将用户该卷号剩余长度重新分配给管理员
 * 恢复剩余长度，将用户该卷号剩余长度增加给管理员
 * */
function deleteDealer($user_id)
{
    return false;
    $admin_id = session()->get('admin.id');
    $user_type = session()->get('admin.user_type');
    if ($user_type != 1) {
        abort(404);
    }
    $model = Admin::findOrFail($user_id);
    if ($model->user_type != 3) {
        abort(404);
    }
    $warranty_id = DB::table('warranty')->where('user_id', $user_id)->get('id');
    $model->warranty_id = $warranty_id;
    $rst = DB::table('roll_restlen')->where('user_id', $user_id)->get(['roll_number', 'restlen']);
    $rid = mrnrid(Arr::pluck($rst, 'roll_number'));
    foreach ($rst as $k => $v) {
        if ($v->restlen > 0) {
            plusRestlen(1, $v->roll_number, $v->restlen);
        }
        if (!empty($rid[$v->roll_number])) {
            addRollSales($rid[$v->roll_number], $user_id, 1, $v->restlen);
        }
    }
    $bool = $model->delete();
    DB::table('roll_restlen')->where('user_id', $user_id)->delete(); // 删除剩余长度信息
    // alogs('经销商', '删除', $model->id, null, $model);
    editUserStatus($model, 4);
    return ['status' => 'SUCCESS', 'msg' => '成功！'];
}
/*
 * 根据卷号查询ID，并返回卷号=》id
 * 删除用户时，同时增加分配记录，将该卷号重新分配给管理员*/
function mrnrid($rns)
{
    $datas = DB::table('roll_master')->whereIn('roll_number', $rns)->get(['id', 'roll_number']);
    $res = [];
    foreach ($datas as $k => $v) {
        $res[$v->roll_number] = $v->id;
    }
    return $res;
}
/*
 * 删除省代*/
function deleteDistributor($user_id)
{
    return false;
    $admin_id = session()->get('admin.id');
    $user_type = session()->get('admin.user_type');
    if ($user_type != 1) {
        abort(404);
    }
    $model = Admin::findOrFail($user_id);
    if ($model->user_type != 2) {
        abort(404);
    }
    $dealer_id = DB::table('users')->where('creator_id', $user_id)->get('id');
    $warranty_id = DB::table('warranty')->where('user_id', $user_id)->get('id');
    $model->warranty_id = $warranty_id;
    $model->dealer_id = $dealer_id;
    foreach ($dealer_id as $k => $v) {
        deleteDealer($v->id);
    }
    foreach ($warranty_id as $k => $v) {
        deleteWarranty($v->id);
    }
    $rst = DB::table('roll_restlen')->where('user_id', $user_id)->get(['roll_number', 'restlen']);
    $rid = mrnrid(Arr::pluck($rst, 'roll_number'));
    foreach ($rst as $k => $v) {
        if ($v->restlen > 0) {
            plusRestlen(1, $v->roll_number, $v->restlen);
        }
        // minusRestlen($user_id, $v->roll_number, $v->restlen);
        if (!empty($rid[$v->roll_number])) {
            addRollSales($rid[$v->roll_number], $user_id, 1, $v->restlen);
        }
    }

    $bool = $model->delete();
    DB::table('roll_restlen')->where('user_id', $user_id)->delete(); // 删除剩余长度信息
    // alogs('省代', '删除', $model->id, null, $model);
    editUserStatus($model, 4);
    return ['status' => 'SUCCESS', 'msg' => '成功！'];
}


function getRollId($roll_number)
{
    $roll = getRollsMasterByRollNumber($roll_number);
    return @$roll->id;
}

function getRollNo($id)
{
    $roll = DB::table('roll_master')->where('id', $id)->first();
    return @$roll->roll_number;
}

/*
 * 根据关键词组筛选*/
function filterByColumns($model, $columns = [], $label = 'value')
{
    if (request()->input($label) !== null) {
        $value = trim(request()->input($label));
        $model = $model->where(function ($query) use ($value, $columns) {
            foreach ($columns as $k => $c) {
                $query->orWhere($c, 'like', '%' . $value . '%');
            }
        });
    }
    return $model;
}
/*
 * 根据日期组筛选*/
function filterByDateRange($model, $column = 'created_at')
{
    $startdate = trim(request()->input('startdate'));
    $enddate = trim(request()->input('enddate'));
    if ($startdate) {
        $startdate = date('Y-m-d 0:0:0', strtotime($startdate));
        $model = $model->where($column, '>=', $startdate);
    }
    if ($enddate) {
        $enddate = date('Y-m-d 23:59:59', strtotime($enddate));
        $model = $model->where($column, '<=', $enddate);
    }
    return $model;
}
/*
 * 剩余表，根据卷号获取剩余长度*/
function getRestlen($ro, $user_id = 0)
{
    $restlen = 0;
    $rr = RollRestlen::where('roll_number', $ro)
        ->where('user_id', $user_id)
        ->first();
    if (empty($rr)) {
        return 0;
    }
    return $rr->restlen;
    $restlen = getRlenV401($ro, $user_id);
    return $restlen;
}

function getPrecutCoverages($id)
{
    return DB::table('precut_to_vehicle_coverage')
        ->where('precut_kit_sale_id', $id)
        ->get();
}
/*
 * 主要为质保、套餐新增或修改时，获取ID，便于获取卷号剩余长度*/
function getIdFromUrl($url = null, $type = 1)
{
    if (empty($url)) {
        if ($type == 1) {
            $url = request()->header('referer');
            if (empty($url)) {
                abort(404);
            }
        } else {
            $url = request()->path();
        }
    }

    $parse_url = parse_url($url);
    $rpath = @$parse_url['path']; // 地址
    if (stripos($rpath, '/admin/warranty/') === 0) {
        $id = str_replace('/admin/warranty/', '', $rpath);
        $id = str_replace('/edit', '', $rpath);
        $id = (int) $id;
    }
    if (stripos($rpath, '/admin/precut/') === 0) {
        $id = str_replace('/admin/precut/', '', $rpath);
        $id = str_replace('/edit', '', $rpath);
        $id = (int) $id;
    }
}
/*
 * 整理提交的数据*/
function cleanCoverages()
{
    $part = request()->input('part');
    $roll_number = request()->input('roll_number');
    $length = request()->input('length');
    $width = request()->input('width');
    $film_type_id = request()->input('film_type_id') ?: [];
    $precut_or_manual = request()->input('precut_or_manual') ?: [];
    $wups = [];
    foreach ($part as $k => $v) {
        $wups[] = [
            'part_id' => $v,
            'roll_number' => @$roll_number[$k],
            'length' => @$length[$k],
            'width' => @$width[$k],
            'film_type_id' => @$film_type_id[$k],
            'precut_or_manual' => @$precut_or_manual[$k],
        ];
    }
    return $wups;
}
/*
 * 获取省代下属经销商
 * 不获取管理员下属省代*/
function getDDealers($id)
{
    return DB::table('users')->where('creator_id', $id)->where('user_type', 3)->get();
}

/*
 * 获取省代及下属经销商业绩*/
function getDDPerformance($id)
{
    return DB::table('warranty')
        ->whereIn('user_id', function ($query) use ($id) {
            $query->select('id')->from('users')
                ->where('id', $id)
                ->orWhere('creator_id', $id);
        })
        ->whereNull('deleted_at')
        ->get();
}
/*
 * 根据用户ID获取用户业绩*/
function getDPerformance($id)
{
    return DB::table('warranty')
        ->where('user_id', $id)
        ->whereNull('deleted_at')
        ->get();
}
/*
 * 根据省代ID/用户ID
 * 判断省代用户的经销商数*/
function getDDN($id)
{
    return DB::table('users')
        ->where('creator_id', $id)
        // ->whereNull('deleted_at')
        ->where('status', '!=', 2)
        ->count('id');
}
/*
 * 判断用户ID的业绩数*/
function getDDPN($id)
{
    return DB::table('warranty')
        ->whereIn('user_id', function ($query) use ($id) {
            $query->select('id')->from('users')
                ->where('id', $id)
                ->orWhere('creator_id', $id);
        })
        ->whereNull('deleted_at')
        ->count('id');
}
/*
 * 判断用户ID的业绩数*/
function getDPN($id)
{
    return DB::table('warranty')
        ->where('user_id', $id)
        ->whereNull('deleted_at')
        ->count('id');
}

/*
 * 将日志文件转移到数据库
 * 其中created_at为日志记录的时间
 * updated_at为当前时间
 * */
function mLtD()
{
    $data = DB::table('db_logs')->orderByDesc('id')
        ->first();
    if (empty($data->created_at)) {
        $date = '2020-11-15';
    } else {
        $date = $data->created_at;
    }
    if ($date < '2020-11-15') {
        $date = '2020-11-15';
    }
    $date = date('Y-m-d', strtotime($date));
    // $date = date('Y-m-d H:i:0');
    //  H:i:s
    $date = date('Y-m-d', strtotime($date));
    $lines = DB::table('db_logs')->where('created_at', '>=', $date)->count('id');
    $log_path = storage_path('logs/mysql/');
    $files = scandir($log_path);
    $logs = [];
    foreach ($files as $k => $v) {
        $p = pathinfo($v);
        $ext = $p['extension'];
        $fm = $p['filename'];
        if ($ext == 'log') {
            if (stripos($fm, 'laravel-') === 0) {
                $logs[$v] = filectime($log_path . $v);
            }
        }
    }
    asort($logs); // 按时间升序排序
    $logs = array_keys($logs);
    $nLogs = [];
    foreach ($logs as $k => $v) {
        $fm = pathinfo($v, PATHINFO_FILENAME);
        $fm = substr($fm, 8);
        if ($fm >= $date) {
            $nLogs[$fm] = $v;
        }
    }
    foreach ($nLogs as $k => $v) {
        if ($k == $date) {
            hLD($log_path . $v, $lines);
        } else {
            hLD($log_path . $v);
        }
    }
    return $nLogs;
}
function hLD($logs, $line = 0)
{
    $handle = @fopen($logs, 'r');
    $datas = [];
    $key = 0;
    $alog = new AbelLogs();
    if ($handle) {
        while (($buffer = fgets($handle)) !== false) {
            if ($key < $line) {
                $key++;
                continue;
            }
            if (empty($buffer)) {
                continue;
            }
            $obj = $alog->parse($buffer);
            if ($obj) {
                $datas[] = $obj;
                if (count($datas) >= 5000) {
                    uLD($datas);
                    $datas = [];
                }
            }
        }
        if (!feof($handle)) {
        }
        fclose($handle);
    }
    if (!empty($datas)) {
        uLD($datas);
    }
}

function uLD($datas)
{
    DB::table('db_logs')->insert($datas);
}
/*
 * 隐藏手机或电话号码，仅展示前三后四
 * 当位数小于7的时候，仅展示前三位*/
function rsPN($no)
{
    $no = trim($no);
    $res = '';
    $len = mb_strlen($no);
    if ($len > 7) {
        $res = mb_substr($no, 0, 3) . '****' . mb_substr($no, -4, 4);
    } elseif ($len > 3) {
        $res = substr($no, 0, 3) . '****';
    } else {
    }
    return $res;
}
/*
 * 获取用户及下属经销商尚未安装的套餐信息
 * 不获取管理员信息
 * */
function getDPDs($user_id)
{
    return DB::table('precut')
        ->whereIn('user_id', function ($query) use ($user_id) {
            $query->select('id')->from('users')
                ->where('users.id', $user_id)
                ->orWhere('creator_id', $user_id);
        })
        ->where('status', '!=', 1)
        ->whereNull('deleted_at')
        ->get(['id', 'precut_id']);
}

/*
 * 套餐
 * 套餐分配*/
function assignPrecut($id, $sold_by_user_id, $sold_to_user_id, $type = 1)
{
    $type = (int) $type ?: 1;
    $model = new PrecutAssign();
    $model->precut_id = $id;
    $model->sold_by_user_id = $sold_by_user_id;
    $model->sold_to_user_id = $sold_to_user_id;
    $model->created_by = session('admin.id');
    $model->type = $type;
    $model->save();
    $alogs = alogs('套餐', '分配', $id, $model, null);
}
/*
 * 单列排序
 * 根据列排序*/
function sortByColumn($model, $columns)
{
    $sort = trim(request()->input('sort'));
    $order = trim(request()->input('order'));
    if (empty($columns[$sort])) {
        return $model;
    }
    if ($order == 'asc') {
        $model = $model->orderBy($columns[$sort]);
    } elseif ($order == 'desc') {
        $model = $model->orderByDesc($columns[$sort]);
    }
    return $model;
}
/*
 * 设置order class*/
function setOrderClass($column)
{
    return request()->input('sort') == $column ? request()->input('order') : '';
}
/*
 * 根据公司名称或简称获取用户ID*/
function getUserIdByName($name)
{
    $user = Admin::withTrashed()->where('abbr', $name)
        // ->orWhere('company_name', $name)
        ->first();
    return @$user->id;
}
/*
 * 根据公司名称或简称获取用户ID*/
function getUserByName($name)
{
    $user = Admin::withTrashed()->where('abbr', $name)
        // ->orWhere('company_name', $name)
        ->first();
    return @$user;
}
class AbelLogs
{
    private $patterns = [
        '/^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}([\+-]\d{4})?)\](?:.*?(\w+)\.|.*?)',
        ': (.*?)( in .*?:[0-9]+)?$/i'
    ];
    private $level = ['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency', 'processed', 'failed'];

    public function __construct() {}

    /*
     * 将日志字符串解析为数组*/
    public function parse($buffer)
    {
        $res = [];
        foreach ($this->level as $level) {
            if (strpos(strtolower($buffer), '.' . $level)) {
                $dd = preg_match($this->patterns[0] . $level . $this->patterns[1], $buffer, $data);
                $obj = json_decode(@$data[4]);
                $res = [
                    'user_id' => @$obj->user_id,
                    'user_type' => @$obj->user_type,
                    'user_name' => @$obj->user_name,
                    'ip' => @$obj->ip,
                    'method' => @$obj->method,
                    'url' => @$obj->url,
                    'table_name' => @$obj->table_name,
                    'operation' => @$obj->operation,
                    'query' => @json_encode(@$obj->query) ?: null,
                    'created_at' => @$data[1],
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
            }
        }
        return $res;
    }
}

/*
 * 经销商同步*/
function gUDId($union_id)
{
    $data = DB::table('users_union')->where('union_id', $union_id)->first();
    if (empty($data)) {
        return 0;
    }
    return $data->user_id ?: 0;
}
function cDUId($unique_id)
{
    if (empty($unique_id)) {
        return ['status' => false, 'msg' => '参数为空！'];
    }
    $mod = Admin::where(['unique_id' => $unique_id])->withTrashed()->get();
    if (count($mod) >= 1) {
        return ['status' => false, 'msg' => ts('Duplicate Records') . ' !'];
    }
    return ['status' => 'SUCCESS', 'msg' => '成功！'];
}

/*
 * 获取语言*/
function getLangName()
{
    $language = (int) session('language') ?: 1;
    if ($language == 1) {
        $lang = 'english_value';
    } elseif ($language == 2) {
        $lang = 'traditional_chiness_value';
    } elseif ($language == 3) {
        $lang = 'simplified_chiness_value';
    } else {
        $lang = 'english_value';
    }
    return $lang;
}
/*
 * 获取装贴部位*/
function getParts()
{
    $lang = getLangName();
    $parts = PartMaster::orderByDesc('id')->get(['id', 'product_type_id', 'min_length', $lang]);
    $part = [];
    foreach ($parts as $k => $v) {
        $part[] = [
            'label' => $v->$lang,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
            'min_length' => $v->min_length,
        ];
    }
    return $part;
}
/*
 * 根据卷号获取卷*/
function getRollN($roll_number)
{
    return RollMaster::withTrashed()
        ->where('roll_number', $roll_number)
        ->first();
}
/*
 * 根据卷号获取卷*/
function getRollNt($roll_number)
{
    return RollMaster::withTrashed()
        ->where('roll_number', $roll_number)
        ->firstOrFail();
}
/*
 * 根据卷号获取卷
 * */
function getRNt2($roll_number)
{
    return RollMaster::where('roll_number', $roll_number)
        ->first();
}
/*
 * 判断卷号是否存在*/
function cRNe($roll_number)
{
    $c = RollMaster::where('roll_number', $roll_number)->count('id');
    return $c;
}
/*
 * 根据质保模型发送短信*/
function sendSMS($warranty)
{
    if (empty($warranty) || $warranty->approved != 1) {
        return [
            'status' => false,
            'msg' => '仅已通过审核的质保可以发送短信通知'
        ];
    }
    $alogs = alogs('短信', '质保短信通知', $warranty->id, null, $warranty);
    $year_id = @$warranty->year_id;
    $make_id = @$warranty->make_id;
    $model_id = @$warranty->model_id;
    $ext = @$warranty->extension;
    $phone_number = @$warranty->phone_number;
    if (!in_array($ext, ['+86', '+886', '+853', '+852'])) {
        $ext = null;
    }
    if (empty($ext)) {
        return ['status' => false, 'msg' => '地区号不能为空！'];
    }
    if (empty($phone_number)) {
        return ['status' => false, 'msg' => '手机号码不能为空！'];
    }
    $makeMaster = \App\Models\MakeMaster::withTrashed()->find($make_id);
    $modelMaster = \App\Models\ModelMaster::withTrashed()->find($model_id);
    // traditional_chiness_value
    // english_value
    $language_id = @$warranty->language_id;
    if ($ext == '+86') {
        $mobile = $phone_number;
        $year = $year_id;
        $make = @$makeMaster->simplified_chiness_value;
        $model = @$modelMaster->simplified_chiness_value ?: $model_id;
        $content = (new \App\Services\SmsService())->getContent(1, $year, $make, $model);
        //$content = '【XPEL】尊敬的客户：谢谢您选择XPEL超跑级保护膜，您的['.$year.' '.$make.' '.$model.']已经成功上传全国统一的电子质保系统。您可以在微信的公众平台搜索“XPEL”并查询真伪。如有问题请咨询XPEL特约授权经销商。www.xpel.com.cn';
        $obj = message_sms_send($ext, $phone_number, $content);
    } else {
        $mobile = $phone_number;
        $year = $year_id;
        $make = @$makeMaster->traditional_chiness_value;
        $model = @$modelMaster->traditional_chiness_value ?: $model_id;
        // http://warranty.xpelfilms.com.cn
        // xpelfilms.dengwho.com
        $content = (new \App\Services\SmsService())->getContent(2, $year, $make, $model);
        //$content = '【XPEL】尊敬的客戶，謝謝您選擇XPEL超跑級漆面保護膜，您的 '.$year.' '.$make.' '.$model.' 已經成功上傳全省統一的電子保固系統，您可以在官方保固網站查詢真偽，如有問題，請諮詢XPEL授權經銷商。www.xpel.com.cn';
        $obj = international_sms_send($ext, $phone_number, $content);
    }
    $params = [
        'ext' => $ext,
        'mobile' => $mobile,
        'content' => $content,
        'res' => @$obj['data'],
    ];

    $alogs->new = $params;
    $alogs->save();

    if (@$obj['status'] == 'SUCCESS') {
        return [
            'status' => 'SUCCESS',
            'msg' => '成功！',
        ];
    } else {
        return [
            'status' => false,
            'msg' => @$obj['msg'],
        ];
    }
}
/*
 * 静态文本查询
 * 根据文字获取ID*/
function getColumnIdByName($table, $name, $lang = 0)
{
    $table = trim($table);
    $name = trim($name);
    if (in_array($table, ['cities', 'film_type_master', 'make_master', 'part_master', 'product_types', 'province_master', 'region_master'])) {
    } else {
        return 0;
    }
    $model = DB::table($table)
        ->orWhere('english_value', $name)
        ->orWhere('traditional_chiness_value', $name)
        ->orWhere('simplified_chiness_value', $name);

    $data = $model->first();
    return @$data->id ?: 0;
}
/*
 * 静态资源
 * 根据名称获取ID*/
function getColumnIdByName2($table, $name, $super = 0)
{
    $table = trim($table);
    $name = trim($name);
    $super = (int) $super;
    if (in_array($table, ['cities', 'film_type_master', 'make_master', 'part_master', 'product_types', 'province_master', 'region_master', 'model_master'])) {
    } else {
        return 0;
    }
    // 中国大陆，香港特别行政区，澳门特别行政区，台湾地区
    if ($table == 'region_master') {
        if ($name == '中国') {
            $name = '中国大陆';
        }
        if ($name == '台湾') {
            $name = '台湾地区';
        }
        if ($name == '澳门') {
            $name = '澳门特别行政区';
        }
        if ($name == '香港') {
            $name = '香港特别行政区';
        }
    }
    if ($table == 'province_master') {
        if (mb_strpos($name, '宁夏') === 0) {
            $name = '宁夏';
        }
        if (mb_strpos($name, '内蒙古') === 0) {
            $name = '内蒙古';
        }
        if (mb_strpos($name, '西藏') === 0) {
            $name = '西藏';
        }
        if (mb_strpos($name, '新疆') === 0) {
            $name = '新疆';
        }
        if (mb_strpos($name, '香港') === 0) {
            $name = '香港';
        }
        if (mb_strpos($name, '澳门') === 0) {
            $name = '澳门';
        }
        if (mb_strpos($name, '台湾') === 0) {
            $name = '台湾';
        }
    }

    $model = DB::table($table)
        ->whereNull('deleted_at')
        ->where(function ($query) use ($name, $table) {
            $name1 = $name . '市';
            $name2 = $name . '省';
            if ($table == 'cities') {
                $query->where('english_value', $name)
                    ->orWhere('traditional_chiness_value', $name)
                    ->orWhere('simplified_chiness_value', $name)
                    ->orWhere('traditional_chiness_value', $name1)
                    ->orWhere('traditional_chiness_value', $name1)
                    ->orWhere('simplified_chiness_value', $name1);
            } elseif ($table == 'province_master') {
                $query->where('english_value', $name)
                    ->orWhere('traditional_chiness_value', $name)
                    ->orWhere('simplified_chiness_value', $name)
                    ->orWhere('traditional_chiness_value', $name1)
                    ->orWhere('traditional_chiness_value', $name1)
                    ->orWhere('simplified_chiness_value', $name1)
                    ->orWhere('traditional_chiness_value', $name2)
                    ->orWhere('traditional_chiness_value', $name2)
                    ->orWhere('simplified_chiness_value', $name2);
            } else {
                $query->where('english_value', $name)
                    ->orWhere('traditional_chiness_value', $name)
                    ->orWhere('simplified_chiness_value', $name);
            }
        });

    if ($super && $super > 0) {
        if ($table == 'cities') {
            $model = $model->where('province_id', $super);
        }
        if ($table == 'province_master') {
            $model = $model->where('region_id', $super);
        }
        if ($table == 'make_master') {
            $model = $model->where('year_id', $super);
        }
        if ($table == 'model_master') {
            $model = $model->where('make_id', $super);
        }
    }

    $data = $model->first();
    return @$data->id ?: 0;
}
function getColumnByName3($table, $name)
{
    $table = trim($table);
    $name = trim($name);
    if (in_array($table, ['film_type_master', 'part_master', 'product_types', 'model_master'])) {
    } else {
        return 0;
    }
    $model = DB::table($table)
        ->whereNull('deleted_at')
        ->where(function ($query) use ($name, $table) {
            $query->where('english_value', $name)
                ->orWhere('traditional_chiness_value', $name)
                ->orWhere('simplified_chiness_value', $name);
        });

    $data = $model->first();
    return $data;
}
function checkRollPart($roll_number, $part)
{
    $roll_number = getRollsMasterByRollNumber($roll_number);
    $rpid = FilmTypeMaster::find(@$roll_number->id);
}

function upload_file()
{
    // $file = $request->file('file', $fileName=null);
    if (empty($file)) {
        return ['status' => 4001, 'name' => '文件不存在'];
    }
    $cmt = $file->getClientMimeType();
    $ext = '';
    if (stripos($cmt, 'image/') === 0) {
        $ext = substr($cmt, 6);
    }
    if (empty($ext)) {
        return ['status' => false, 'msg' => '仅支持上传图片格式'];
    } else {
        $ext = '.' . $ext;
    }
    $fileName = Str::random(32) . $ext;
}

/*
* 图片上传，保存在本地*/
function uploadFile($file, $fileName)
{
    $accessKey = env('QINIUYUN_ACCESS_KEY');
    $secretKey = env('QINIUYUN_SECRET_KEY');
    $auth = new \Qiniu\Auth($accessKey, $secretKey);
    $bucket = 'warranty-xpel';
    $uploadMgr = new \Qiniu\Storage\UploadManager();
    $token = $auth->uploadToken($bucket);
    list($ret, $error) = $uploadMgr->putFile($token, $fileName, $file);
    if ($error !== null) {
        return ['status' => false, 'msg' => '图片上传失败'];
    }
    $host = env('QINIUYUN_SECRET_HOST');
    return ['status' => 'SUCCESS', 'data' => [
        'url' => $ret['key'],
        'host' => $host
    ]];
}

/*
     * 新版上传，图片保存在七牛云*/
function uploadFileV1($file, $fileName)
{
    $accessKey = env('QINIUYUN_ACCESS_KEY');
    $secretKey = env('QINIUYUN_SECRET_KEY');
    $auth = new \Qiniu\Auth($accessKey, $secretKey);
    $bucket = 'warranty-xpel';
    $uploadMgr = new \Qiniu\Storage\UploadManager();
    $token = $auth->uploadToken($bucket);
    list($ret, $error) = $uploadMgr->putFile($token, $fileName, $file);
    if ($error !== null) {
        return ['status' => false, 'msg' => '图片上传失败'];
    }
    $host = env('QINIUYUN_SECRET_HOST');
    return ['status' => 'SUCCESS', 'data' => [
        'url' => $ret['key'],
        'host' => $host
    ]];
}
/*
 * 获取当前日期，年月日时分秒*/
function gDate()
{
    return date('Y-m-d H:i:s');
}

/*
 * 根据年份、名称获取品牌ID*/
function getMakeId($make_name, $year)
{
    $model = \App\Models\MakeMaster::where('year_id', $year)
        ->where(function ($query) use ($make_name) {
            $query->where('english_value', $make_name)
                ->orWhere('traditional_chiness_value', $make_name)
                ->orWhere('simplified_chiness_value', $make_name);
        })
        ->first();
    return @$model->id ?: 0;
}
/*
 * 根据品牌、名称获取车型ID*/
function getModelId($model_name, $make_id)
{
    $model = \App\Models\ModelMaster::where('make_id', $make_id)
        ->where(function ($query) use ($model_name) {
            $query->where('english_value', $model_name)
                ->orWhere('traditional_chiness_value', $model_name)
                ->orWhere('simplified_chiness_value', $model_name);
        })
        ->first();
    return @$model->id ?: 0;
}
/*
 * V3*/

/*
 * 获取浏览器传入的质保装贴部位数据
 * 专车专用套件逻辑不变*/
function wazbw()
{
    $part = request()->input('part') ?: [];
    $roll_number = request()->input('roll_number');
    $length = request()->input('length');
    $width = request()->input('width');
    $film_type_id = request()->input('film_type_id') ?: [];
    $precut_or_manual = request()->input('precut_or_manual') ?: [];
    $wups = [];
    foreach ($part as $k => $v) {
        $roll = getRollsMasterByRollNumber(@$roll_number[$k]);
        $wups[] = [
            'part_id' => $v,
            'roll_number' => @$roll_number[$k],
            'length' => @$length[$k],
            'width' => @$roll->width ?: @$width[$k],
            'film_type_id' => @$roll->film_type_id ?: @$film_type_id[$k],
            'precut_or_manual' => @$precut_or_manual[$k],
        ];
    }
    return $wups;
}
/*
 * 质保审核V3
 * 审核质保信息
 * 审核安装图片，数量不少于6张*/
function checkWarrantyV3($id)
{
    $w = Warranty::findOrFail($id); // 获取质保
    $f = [
        'user_id' => '装贴门店',
        'first_name' => '车主姓名',
        'phone_number' => '联系电话',
        'email_address' => '电子邮件',

        'region_id' => '区域',
        'province_id' => '省份',
        'city' => '城市',
        'address' => '车主地址',

        'year_id' => '车辆年份',
        'make_id' => '车辆品牌',
        'model_id' => '车辆型号',
        'license_plate' => '牌照号',
        'vin_number' => '车架号',

        'installer_name' => '装贴技师',
        'installation_date' => '装贴日期',
        'installation_price' => '装贴价格',
    ];
    $res = [];
    $msg = [];
    $wvs = [];
    foreach ($f as $k => $v) {
        $kk = trim($w->$k);
        if (empty($kk)) {
            $msg[] = $v . ' 不能为空！';
        }
    }
    if ($w->user_id && !checkDealerBelongs($w->user_id)) {
        if (empty($res)) {
            $res = ['status' => false, 'msg' => '只能操作自己及下属门店的数据！']; // 此处返回错误，但是不保存到消息
        }
    }
    // $images = DB::table('warranty_image')->where('warranty_id', $w->id)->count('id');
    $images = WarrantyImage::where('warranty_id', $w->id)->count('id');
    if ($images >= 6 && $images <= 12) {
    } else {
        $msg[] = '安装图片保证清晰且最多12张，最少6张！';
    }

    if (empty($w->warranty_id)) {
        $w->warranty_id = makeWarrantyId($w->installation_date);
        $w->save(); // 需要保存数据
    }
    if (empty($w->pre_id)) {
        $wv = DB::table('warranty_to_vehicle_coverage')->where('warranty_id', $w->id)->get(['part_id', 'length', 'roll_number']); // 获取卷号
        checkPartItemsV3($wv, $w->user_id, $msg);
    } else {
        $pre = Precut::find($w->pre_id);
        if (empty($pre)) {
            $msg[] = '专车专用套件不存在';
        } else {
            if ($pre->user_id != $w->user_id) {
                $msg[] = '专车专用套件与装贴门店不匹配！';
            }
        }
    }
    if (!empty($msg)) {
        $msgModel = new WarrantyMsg();
        $msgModel->content = json_encode($msg);
        $msgModel->warranty_id = $w->id;
        $msgModel->status = 0;
        $msgModel->save();
    }
    /*
     * 当返回内容为空时，判断提示消息是否存在
     * 否则直接返回内容，有些内容仅做提示不需要保存到系统消息提示中*/
    if (empty($res)) {
        if (empty($msg)) {
            foreach ($wv as $k => $v) {
                // minusRestlen($w->user_id, $v->roll_number, $v->length); // 发起审核时更新剩余长度
            }
            return ['status' => 'SUCCESS', 'msg' => '质保审核发起成功！'];
        } else {
            return ['status' => false, 'msg' => $msg[0], 'items' => $wv]; // 此处返回错误
        }
    }

    return $res;
}

/*
 * 检查质保装贴部位数据
 * 仅发起审核时判断
 * 不判断专车专用套件，仅判断质保*/
function checkPartItemsV3($items, $user_id, &$msg = [])
{
    // $items = (array) $items;
    $wvs = [];
    $status = 'SUCCESS';
    $datas = [];
    $rns = Arr::pluck($items, 'roll_number'); // 卷号可能有重复
    $pts = Arr::pluck($items, 'part_id');
    $pr1 = $pr2 = [];
    foreach ($rns as $k => $v) {
        if (!empty($v)) {
            $pr1[] = $v;
        }
    }
    foreach ($pts as $k => $v) {
        if (!empty($v)) {
            $pr2[] = $v;
        }
    }
    if (empty($pr1)) {
        // $msg[] = "膜卷号 不能为空！";
    }
    if (empty($pr2)) {
        // $msg[] = "装贴部位 不能为空！";
    }
    if (empty($pr2) && empty($pr2)) {

        // return false;
    }

    // ->whereNull('deleted_at')
    // ->whereNull('deleted_at')
    $rolls = DB::table('roll_master')
        ->whereIn('roll_number', $rns)
        ->get(['id', 'roll_number', 'width', 'film_type_id', 'deleted_at']); // 所有卷号
    $parts = DB::table('part_master')
        ->whereIn('id', $pts)
        ->get(['id', 'min_length', 'deleted_at']); // 装贴部位

    if (count($rolls) < 1) {
        // $msg[] = "膜卷号 不能为空；"; // .json_encode($rns);
    }
    if (count($parts) < 1) {
        // $msg[] = "装贴部位 不能为空；"; // .json_encode($pts);
    }
    if (count($rolls) < 1 || count($parts) < 1) {
        // return $msg; // 此处需要返回
    }
    $ras = $pms = $rrs = []; // 各卷号剩余长度
    $rsts = []; // 各卷号剩余长度
    $rnss2 = array_unique($rns);
    $drl = []; // 卷号删除记录
    $dpl = []; // 装贴部位删除记录
    if (!empty($user_id)) {
        foreach ($rnss2 as $k => $v) {
            $rsts[$v] = getRlenV401($v, $user_id);
        }
    }
    foreach ($rolls as $k => $v) {
        $ras[$v->roll_number] = @$rsts[$v->roll_number] ?: 0; // 主表，剩余表数据可能不一致
        $drl[$v->roll_number] = @$v->deleted_at;
    }
    foreach ($parts as $k => $v) {
        $pms[$v->id] = $v->min_length; // 装贴部位最小长度，同时整理装贴部位
        $dpl[$v->id] = @$v->deleted_at;
    }
    $pis = $ris = [];
    foreach ($items as $k => $v) {
        $state = true;
        if (empty($v->part_id)) {
            $msg[] = "装贴部位 不能为空！";
        } elseif (!isset($pms[$v->part_id])) {
            $msg[] = "装贴部位 不存在：" . $v->part_id;
            // $state = false;
        } elseif (!empty($dpl[$v->part_id])) {
            $msg[] = "装贴部位 已被删除：" . ts('part_master.' . $v->part_id);
            // $state = false;
        }
        if (empty($v->roll_number)) {
            $msg[] = "膜卷号 不能为空！";
        } elseif (!isset($ras[$v->roll_number])) {
            $msg[] = "膜卷号 不存在：" . $v->roll_number;
            $state = false;
        } elseif (!empty($drl[$v->roll_number])) {
            $msg[] = "膜卷号 已被删除：" . $v->roll_number;
            $state = false;
        }
        if (!$state == false) {
            // continue;
        }
        if ($v->part_id) {
            $pis[$v->part_id] = @$pis[$v->part_id] + $v->length; // 装贴部位
        }
        $ris[$v->roll_number] = @$ris[$v->roll_number] + $v->length; // 卷号使用长度，这里卷号已经是全部在数据库存在的卷号
        if ($v->length < @$pms[$v->part_id] && !in_array($v->part_id, [150, 152, 153])) {
            $msg[] = ts('part_master.' . $v->part_id) . " 用料长度不得小于 ：" . @$pms[$v->part_id] . ' cm';
            // continue;
        }
    }
    /*小车与全车判断总长度*/
    if (isset($pis[18]) && $pis[18] < 1000) {
        $msg[] = ts('part_master.18') . ' 使用总长度不小于 1000 cm';
    }
    if (isset($pis[40]) && $pis[40] < 850) {
        $msg[] = ts('part_master.40') . '  使用总长度不小于 850 cm';
    }

    if (isset($pis[150]) && $pis[150] < 1000) {
        $msg[] = ts('part_master.150') . ' 使用总长度不小于 1000 cm';
    }
    if (isset($pis[152]) && $pis[152] < 850) {
        $msg[] = ts('part_master.152') . ' 使用总长度不小于 850 cm';
    }
    if (isset($pis[153]) && $pis[153] < 500) {
        $msg[] = ts('part_master.153') . ' 使用总长度不小于 500 cm';
    }
    if (!empty($user_id)) {
        foreach ($ris as $k => $l) {
            if ($l > @$rsts[$k] && isset($ras[$k]) && empty($drl[$k])) {
                $msg[] = $k . ' 门店下卷号剩余可使用长度不足！';
                // continue;
            }
        }
    } else {
        foreach ($ris as $k => $l) {
            if ($l > @$rsts[$k] && isset($ras[$k]) && empty($drl[$k])) {
                $msg[] = $k . " 该卷号不属于该门店；";
                // continue;
            }
        }
    }
    // dd($msg);
    return $msg;
}
/*
 * 判断专车专用套件是否属于用户*/

function textColor($id)
{
    if ($id == 1) {
        return 'text-success';
    } elseif ($id == 2) {
        return 'text-danger';
    }
    return '';
}

/*
 * 重置日期
 * 格式化日期*/
function fdate($date)
{
    $s1 = strtotime($date);
    if ($s1 > strtotime('1997-07-01')) {
        return date('Y-m-d', $s1);
    }
    return '';
}
/*
 * 重置日期
 * 格式化日期*/
function fdate2($date)
{
    $s1 = strtotime($date);
    if ($s1 > strtotime('1997-07-01')) {
        return date('Y-m-d', $s1);
    }
    return '';
}


function getMenuText($role_id)
{
    $role_id = (int) $role_id ?: session('admin.id');
    $role = Roles::findOrFail($role_id);
    $ps = $role->permissions()->get(['id', 'simplified_chiness_value']);
    $pids = Arr::pluck($ps, 'id');

    $data = Permissions::orderBy('id')->get();
    $p1 = [];
    $p2 = [];
    foreach ($data as $k => $v) {
        $p1[$v->id] = $v->simplified_chiness_value;
        if ($v->parent_id == 0) {
            if (empty($p2[$v->id])) {
                $p2[$v->id] = [];
            }
            $p2[$v->id]['label'] = $v->simplified_chiness_value;
            $p2[$v->id]['value'] = $v->id;
            $p2[$v->id]['children'] = @$p2[$v->id]['children'] ?: [];
        } else {
            if (empty($v->parent_id)) {
                $p2[$v->parent_id] = [];
            }
            $p2[$v->parent_id]['label'] = @$p1[$v->parent_id];
            $p2[$v->parent_id]['value'] = $v->parent_id;
            $p2[$v->parent_id]['children'] = @$p2[$v->parent_id]['children'] ?: [];
            $item = [
                'label' => $v->simplified_chiness_value,
                'value' => $v->id,
            ];
            if (in_array($v->id, $pids)) {
                $p2[$v->parent_id]['checked'] = 1;
                $item['checked'] = 1;
            }
            $p2[$v->parent_id]['children'][] = $item;
        }
    }
    return $p2;
}
/*
 * 转换为3个数组*/
function l3region()
{
    $region = \App\Models\RegionMaster::get(['id', 'english_value', 'traditional_chiness_value', 'simplified_chiness_value']);
    $l1 = $l2 = $l3 = [];
    foreach ($region as $k => $v) {
        $l1[$v->english_value] = $v->id;
        $l2[$v->traditional_chiness_value] = $v->id;
        $l3[$v->simplified_chiness_value] = $v->id;
    }
    return [$l1, $l2, $l3];
}
function l3province()
{
    $region = \App\Models\ProvinceMaster::get(['id', 'english_value', 'traditional_chiness_value', 'simplified_chiness_value']);
    $l1 = $l2 = $l3 = [];
    foreach ($region as $k => $v) {
        $l1[$v->english_value] = $v->id;
        $l2[$v->traditional_chiness_value] = $v->id;
        $l3[$v->simplified_chiness_value] = $v->id;
    }
    return [$l1, $l2, $l3];
}
function l3city()
{
    $region = \App\Models\Cities::get(['id', 'english_value', 'traditional_chiness_value', 'simplified_chiness_value']);
    $l1 = $l2 = $l3 = [];
    foreach ($region as $k => $v) {
        $l1[$v->english_value] = $v->id;
        $l2[$v->traditional_chiness_value] = $v->id;
        $l3[$v->simplified_chiness_value] = $v->id;
    }
    return [$l1, $l2, $l3];
}
function l3id($lang, $lan)
{
    [$l1, $l2, $l3] = $lang;
    if (!empty($l1[$lan])) {
        return $l1[$lan];
    }
    if (!empty($l2[$lan])) {
        return $l2[$lan];
    }
    if (!empty($l3[$lan])) {
        return $l3[$lan];
    }
    return 0;
}

/*
 * 将省代Excel数据转化为符合系统规则的键值对
 * 根据unique_id判断，不再使用id
 * unique与3*/
function ped1($data)
{
    $region = l3region(); // 地区
    $province = l3province(); // 省
    $city = l3city(); // 城市
    $res = [];
    $l = [
        'A' => 'id',
        'B' => 'unique_id',
        'C' => 'password',
        'D' => 'abbr',
        'E' => 'company_name',
        'F' => 'extension',
        'G' => 'phone_number',
        'H' => 'email_address',
        'I' => 'status',
        'J' => 'region_id',
        'K' => 'province_id',
        'L' => 'city',
        'M' => 'address',
        'N' => 'first_name',
        'O' => 'cell_phone',
        'P' => 'wechat_id',
        'Q' => 'note',
    ];
    foreach ($data as $k => $v) {
        $item = [];
        foreach ($l as $j => $m) {
            $item[$m] = $v[$j];
        }
        /*status、region_id、province_id、city*/
        $item['status'] = $item['status'] == '启用' ? 1 : 0;
        $item['region_id'] = l3id($region, $item['region_id']);
        $item['province_id'] = l3id($province, $item['province_id']);
        $item['city'] = l3id($city, $item['city']);
        /*creator_id, user_type, mdtype*/
        $item['creator_id'] = 0;
        $item['user_type'] = 2;
        $item['mdtype'] = 0;
        /*结束*/
        $res[] = $item;
    }
    return $res;
}
/*
 * 检查目前省代与传入是否一致
 * 5不存在提示新增
 * 0存在有变化提示修改
 * 2存在无变化提示正常*/
function ced1($unique_id, $array)
{
    // $model = Admin::find($id);
    $model = Admin::where(['unique_id' => $unique_id])->first();
    if (empty($model) || empty($model->id)) {
        return 5;
    }
    $l = [
        // 'A' => 'id',
        'B' => 'unique_id',
        // 'C' => 'password',
        'D' => 'abbr',
        'E' => 'company_name',
        'F' => 'extension',
        'G' => 'phone_number',
        'H' => 'email_address',
        'I' => 'status',
        'J' => 'region_id',
        'K' => 'province_id',
        'L' => 'city',
        'M' => 'address',
        'N' => 'first_name',
        'O' => 'cell_phone',
        'P' => 'wechat_id',
        // 'Q' => 'note',
    ];
    foreach ($l as $k => $v) {
        if ($model->$v == $array[$v]) {
            continue;
        } else {
            return 0;
        }
    }
    return 2;
}


/*
 * 将经销商Excel数据转化为符合系统规则的键值对*/
function ped2($data)
{
    $region = l3region(); // 地区
    $province = l3province(); // 省
    $city = l3city(); // 城市
    $res = [];
    $l = [
        'A' => 'unique_id', // 账号
        'B' => 'mdtype', // 等级
        'C' => 'creator_id',
        'D' => 'abbr', // 名称
        'E' => 'company_name',
        'F' => 'extension',
        'G' => 'phone_number',
        'H' => 'email_address',
        'I' => 'status', // 状态
        'J' => 'region_id', // 区域
        'K' => 'province_id', // 省
        'L' => 'city', // 城市
        'M' => 'address', // 地址
        'N' => 'first_name',
        'O' => 'cell_phone',
        'P' => 'wechat_id',
        'Q' => 'note',
    ];
    foreach ($data as $k => $v) {
        $item = [];
        foreach ($l as $j => $m) {
            $item[$m] = trim($v[$j]);
        }
        /*status、region_id、province_id、city*/
        $item['status'] = $item['status'] == '启用' ? 1 : 0;
        $item['region_id'] = l3id($region, $item['region_id']);
        $item['province_id'] = l3id($province, $item['province_id']);
        $item['city'] = l3id($city, $item['city']);
        /*creator_id, user_type, mdtype*/
        // $item['creator_id'] = 0;
        $item['user_type'] = 3;
        $item['mdtype'] = getMdTypeID($item['mdtype']);
        /*结束*/
        $res[] = $item;
    }
    return $res;
}
/*
 * 检查目前经销商与传入是否一致*/
function ced2($id, $array)
{
    $model = Admin::withTrashed()->where('unique_id', $id)->first();
    if (empty($model->id)) {
        return 5;
    }
    $l = [
        'A' => 'unique_id',
        'B' => 'mdtype',
        // 'C' => 'creator_id',
        'D' => 'abbr',
        // 'E' => 'company_name',
        // 'F' => 'extension',
        // 'G' => 'phone_number',
        // 'H' => 'email_address',
        'I' => 'status',
        'J' => 'region_id',
        'K' => 'province_id',
        'L' => 'city',
        'M' => 'address',
        // 'N' => 'first_name',
        // 'O' => 'cell_phone',
        // 'P' => 'wechat_id',
        // 'Q' => 'note',
    ];
    foreach ($l as $k => $v) {
        if ($model->$v == $array[$v]) {
            continue;
        } else {
            return 0;
        }
    }
    return 2;
}

/*
 * 根据传入字段返回门店等级*/
function getMdTypeID($name)
{
    $name = trim($name);
    if ($name == '外星人店') {
        return 1;
    }
    if ($name == '授权店') {
        return 2;
    }
    if ($name == '直营店') {
        return 3;
    }
    if ($name == '旗舰店') {
        return 4;
    }
    return 0;
}

/*
 * 将对象改为label-value数组对*/
function ldv($data, $l) {}

/*
 * 根据用户模型返回用户状态*/
function fdu1($admin)
{
    if (empty($admin->id)) {
        return ts('YHBCZ');
    }
    if (!empty($admin->deleted_at)) {
        return ts('jy');
    }
    return ts('ust' . $admin->status);
}

/*
 * 生成含大小写、数字、随机标点符号的密码*/
function makePassword($no = 16)
{
    $int = range(0, 9);
    $lower = range('a', 'z');
    $upper = range('A', 'Z');
    $fs = ['!', '@', '#', '$', '%', '^', '&', '*'];
    $all = array_merge($int, $lower, $upper, $fs);
    $pw = [];
    $pwa = [];
    $len = count($all);
    if ($no < 4) {
        $pwa = array_rand($all, 4);
    } else {
        $pwa[] = rand(0, 9);
        $pwa[] = rand(0, 25) + 10;
        $pwa[] = rand(0, 25) + 10 + 26;
        $pwa[] = rand(62, $len - 1);
        for ($i = 5; $i <= $no; $i++) {
            $pwa[] = rand(0, $len - 1);
        }
    }
    foreach ($pwa as $v) {
        $pw[] = $all[$v];
    }
    shuffle($pw);
    return implode('', $pw);
}

/*
 * 生产全部语言文件*/
function makeLangFiles()
{
    $tables = [
        'cities',
        'province_master',
        'region_master',
        'macro_management',
        'product_types',
        'make_master',
        'part_master',
        'film_type_master',
        'product_type_master',
        'model_master',
        'new_precut_part',
    ];
    $e = [];
    foreach ($tables as $table) {
        $e[] = makeLangFile($table);
    }

    $e[] = make_json_data();
    $e[] = regions_json_data();
    $e[] = coverages_json_data();

    $e[] = new_precut_json_data();
}
/*
 * 生成前端JS*/
function make_json_data()
{
    $datas = MakeMaster::get();
    $year = $make = $res_model = [];
    $make_en = $make_zh_tw = $make_zh = [];
    $model_en = $model_zh_tw = $model_zh = [];
    $make_zh[] = $make_zh_tw[] = $make_en[] = [
        'label' => null,
        'value' => null,
        'year_id' => null,
    ];
    foreach ($datas as $k => $v) {
        $year[$v->year_id] = 1;
        $make_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
            'year_id' => $v->year_id,
        ];
        $make_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
            'year_id' => $v->year_id,
        ];
        $make_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
            'year_id' => $v->year_id,
        ];
    }
    $year = array_keys($year);
    rsort($year);
    $years = [];
    $years[] = [
        'label' => null,
        'value' => null,
    ];
    foreach ($year as $k => $v) {
        $years[] = [
            'label' => $v,
            'value' => $v,
        ];
    }
    $datas = ModelMaster::get();
    $model_en[] = $model_zh_tw[] = $model_zh[] = [
        'label' => null,
        'value' => null,
        'make_id' => null,
    ];
    foreach ($datas as $k => $v) {
        $model_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
            'make_id' => $v->make_id,
        ];
        $model_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
            'make_id' => $v->make_id,
        ];
        $model_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
            'make_id' => $v->make_id,
        ];
    }
    $dir = public_path('/dist/admin/');
    $filename = 'make_json_data';
    $data_en = [
        'year' => $years,
        'make' => $make_en,
        'model' => $model_en,
    ];
    $string = 'window.makes_data=' . json_encode($data_en);
    file_put_contents($dir . $filename . '_1.js', $string);
    unset($data_en);
    unset($make_en);
    unset($model_en);
    $data_zh_tw = [
        'year' => $years,
        'make' => $make_zh_tw,
        'model' => $model_zh_tw,
    ];
    $string = 'window.makes_data=' . json_encode($data_zh_tw);
    file_put_contents($dir . $filename . '_2.js', $string);
    unset($data_zh_tw);
    unset($make_zh_tw);
    unset($model_zh_tw);
    $data_zh = [
        'year' => $years,
        'make' => $make_zh,
        'model' => $model_zh,
    ];
    $string = 'window.makes_data=' . json_encode($data_zh);
    file_put_contents($dir . $filename . '.js', $string);
    file_put_contents($dir . $filename . '_3.js', $string);
    unset($data_zh);
    unset($make_zh);
    unset($model_zh);
    unset($years);
    return;
}

function regions_json_data()
{
    $region = RegionMaster::get();
    $province = ProvinceMaster::get();
    $city = Cities::get();

    $region_en = $region_zh_tw = $region_zh = [];
    $province_en = $province_zh_tw = $province_zh = [];
    $city_en = $city_zh_tw = $city_zh = [];

    $region_en[] = $region_zh_tw[] = $region_zh[] = [
        'label' => null,
        'value' => null,
    ];
    foreach ($region as $k => $v) {
        $region_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
        ];
        $region_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
        ];
        $region_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
        ];
    }

    $province_en[] = $province_zh_tw[] = $province_zh[] = [
        'label' => null,
        'value' => null,
        'region_id' => null,
    ];
    foreach ($province as $k => $v) {
        $province_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
            'region_id' => $v->region_id,
        ];
        $province_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
            'region_id' => $v->region_id,
        ];
        $province_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
            'region_id' => $v->region_id,
        ];
    }

    $city_en[] = $city_zh_tw[] = $city_zh[] = [
        'label' => null,
        'value' => null,
        'province_id' => null,
    ];
    foreach ($city as $k => $v) {
        $city_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
            'province_id' => $v->province_id,
        ];
        $city_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
            'province_id' => $v->province_id,
        ];
        $city_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
            'province_id' => $v->province_id,
        ];
    }
    $dir = public_path('/dist/admin/');
    $filename = 'regions_json_data';
    $data_en = [
        'region' => $region_en,
        'province' => $province_en,
        'city' => $city_en,
    ];
    $string = 'window.regions_data=' . json_encode($data_en);
    file_put_contents($dir . $filename . '_1.js', $string);
    unset($data_en);
    unset($region_en);
    unset($province_en);
    unset($city_en);
    $data_zh_tw = [
        'region' => $region_zh_tw,
        'province' => $province_zh_tw,
        'city' => $city_zh_tw,
    ];
    $string = 'window.regions_data=' . json_encode($data_zh_tw);
    file_put_contents($dir . $filename . '_2.js', $string);
    unset($data_zh_tw);
    unset($region_zh_tw);
    unset($province_zh_tw);
    unset($city_zh_tw);
    $data_zh = [
        'region' => $region_zh,
        'province' => $province_zh,
        'city' => $city_zh,
    ];
    $string = 'window.regions_data=' . json_encode($data_zh);
    file_put_contents($dir . $filename . '.js', $string);
    file_put_contents($dir . $filename . '_3.js', $string);
    unset($data_zh);
    unset($region_zh);
    unset($province_zh);
    unset($city_zh);
    return;
}

function coverages_json_data()
{
    $parts = PartMaster::orderBy('order', 'asc')
        ->orderBy('id')
        ->get();
    $film_types = FilmTypeMaster::orderBy('order', 'asc')
        ->orderBy('id')
        ->get();
    $widths = [61, 76, 92, 152];

    $parts_en = $parts_zh_tw = $parts_zh = [];
    $film_types_en = $film_types_zh_tw = $film_types_zh = [];
    $parts_en[] = $parts_zh_tw[] = $parts_zh[] = [
        'label' => null,
        'value' => null,
        'product_type_id' => null,
        'min_length' => null,
    ];
    foreach ($parts as $k => $v) {
        $parts_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
            'min_length' => $v->min_length,
        ];
        $parts_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
            'min_length' => $v->min_length,
        ];
        $parts_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
            'min_length' => $v->min_length,
        ];
    }

    $film_types_en[] = $film_types_zh_tw[] = $film_types_zh[] = [
        'label' => null,
        'value' => null,
        'product_type_id' => null,
    ];
    foreach ($film_types as $k => $v) {
        $film_types_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
        ];
        $film_types_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
        ];
        $film_types_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
        ];
    }
    $width = [];
    foreach ($widths as $k => $v) {
        $width[] = [
            'label' => $v,
            'value' => $v,
        ];
    }

    $dir = public_path('/dist/admin/');
    $filename = 'coverages_json_data';
    $data_en = [
        'part' => $parts_en,
        'filmtype' => $film_types_en,
        'width' => $width,
    ];
    $string = 'window.coverages_data=' . json_encode($data_en);
    file_put_contents($dir . $filename . '_1.js', $string);
    unset($data_en);
    unset($parts_en);
    unset($film_types_en);
    $data_zh_tw = [
        'part' => $parts_zh_tw,
        'filmtype' => $film_types_zh_tw,
        'width' => $width,
    ];
    $string = 'window.coverages_data=' . json_encode($data_zh_tw);
    file_put_contents($dir . $filename . '_2.js', $string);
    unset($data_zh_tw);
    unset($parts_zh_tw);
    unset($film_types_zh_tw);
    $data_zh = [
        'part' => $parts_zh,
        'filmtype' => $film_types_zh,
        'width' => $width,
    ];
    $string = 'window.coverages_data=' . json_encode($data_zh);
    file_put_contents($dir . $filename . '.js', $string);
    file_put_contents($dir . $filename . '_3.js', $string);
    unset($data_zh);
    unset($parts_zh);
    unset($film_types_zh);
    unset($width);
    return;
}
/*
 * 新的专车专用套件*/
function new_precut_json_data()
{
    $parts = NewPrecutPart::orderByDesc('order')->orderByDesc('id')->get();
    $products = ProductTypes::orderBy('id')->get();

    $parts_en = $parts_zh_tw = $parts_zh = [];
    $product_type_en = $product_type_zh_tw = $product_type_zh = [];
    $parts_en[] = $parts_zh_tw[] = $parts_zh[] = [
        'label' => null,
        'value' => null,
        'product_type_id' => null,
        'min_length' => null,
        'type' => null,
    ];
    $product_type_en[] = $product_type_zh_tw[] = $product_type_zh[] = [
        'label' => null,
        'value' => null,
    ];
    foreach ($parts as $k => $v) {
        $parts_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
            'min_length' => $v->min_length,
            'type' => $v->type,
        ];
        $parts_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
            'min_length' => $v->min_length,
            'type' => $v->type,
        ];
        $parts_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
            'product_type_id' => $v->product_type_id,
            'min_length' => $v->min_length,
            'type' => $v->type,
        ];
    }
    foreach ($products as $k => $v) {
        $product_type_en[] = [
            'label' => $v->english_value,
            'value' => $v->id,
        ];
        $product_type_zh_tw[] = [
            'label' => $v->traditional_chiness_value,
            'value' => $v->id,
        ];
        $product_type_zh[] = [
            'label' => $v->simplified_chiness_value,
            'value' => $v->id,
        ];
    }

    $dir = public_path('/dist/admin/');
    $filename = 'new_precut_json_data';
    $data_en = [
        'part' => $parts_en,
        'product_type' => $product_type_en,
    ];
    $string = 'window.new_precut_json_data=' . json_encode($data_en);
    file_put_contents($dir . $filename . '_1.js', $string);
    unset($data_en);
    unset($parts_en);
    unset($film_types_en);
    $data_zh_tw = [
        'part' => $parts_zh_tw,
        'product_type' => $product_type_zh_tw,
    ];
    $string = 'window.new_precut_json_data=' . json_encode($data_zh_tw);
    file_put_contents($dir . $filename . '_2.js', $string);
    unset($data_zh_tw);
    unset($parts_zh_tw);
    unset($film_types_zh_tw);
    $data_zh = [
        'part' => $parts_zh,
        'product_type' => $product_type_zh,
    ];
    $string = 'window.new_precut_json_data=' . json_encode($data_zh);
    file_put_contents($dir . $filename . '.js', $string);
    file_put_contents($dir . $filename . '_3.js', $string);
    unset($data_zh);
    unset($parts_zh);
    unset($film_types_zh);
    unset($width);
    return;
}

function checkJsFileExist()
{
    $language = (int) session('language') ?: 1;
    if (!in_array($language, [1, 2, 3])) {
        $language = 1;
    }
    $dir = public_path('/dist/admin/');
    $filename = 'make_json_data_' . $language . '.js';
    if (!file_exists($dir . $filename)) {
        make_json_data();
    }
    $filename = 'regions_json_data_' . $language . '.js';
    if (!file_exists($dir . $filename)) {
        regions_json_data();
    }
    $filename = 'coverages_json_data_' . $language . '.js';
    if (!file_exists($dir . $filename)) {
        coverages_json_data();
    }

    $filename = 'new_precut_json_data_' . $language . '.js';
    if (!file_exists($dir . $filename)) {
        new_precut_json_data();
    }
}
/* 存储*/
function getFileStorePath($type = 1)
{
    // 2 => 内存储，默认公共存储
    $path = '/upload/' . date('Ym') . '/';
    if ($type == 2) {
        $basePath = storage_path('app' . $path);
    } else {
        $basePath = public_path($path);
    }
    if (!file_exists($basePath)) {
        Storage::makeDirectory($basePath, 0755);
    }
    return [
        $basePath,
        $path,
        'base' => $basePath,
        'path' => $path,
    ];
}

/*
 * 生成六位数字验证码*/
function makeSMSCode($no = 6)
{
    $code = '';
    for ($i = 0; $i < $no; $i++) {
        $code .= rand(0, 9);
    }
    return $code;
}

/*
 * 根据手机号发送短信验证码
 * 该手机号超过今日发送限额*/
function sendSMSCode($phone, $type, $ext = '+86')
{
    if (empty($phone)) {
        return fs403('手机号不能为空');
    }
    $count = SmsCode::where('phone', $phone)->where('created_at', '>=', date('Y-m-d'))->count('id');
    if ($count > 40) {
        return fs403('手机号异常，请联系管理员！');
    }
    $ext = trim($ext);
    $phone_number = trim($phone);
    if (!in_array($ext, ['+86', '+886', '+853', '+852'])) {
        $ext = null;
    }
    if (empty($ext)) {
        return fs403('地区号不能为空');
    }
    if (empty($phone_number)) {
        return fs403('手机号码不能为空');
    }

    $code = makeSMSCode();
    if ($ext == '+86') {
        $mobile = $phone_number;
        $content = '【XPEL保护膜认证店】验证码：' . $code . '，切勿将验证码告知他人。';
        $obj = message_sms_send($ext, $phone_number, $content);
    } else {
        $mobile = $phone_number;
        $content = in_array($ext, ['+886', '+853', '+852']) ? '【XPEL保护膜认证店】驗證碼：' . $code . '，切勿將驗證碼告知他人。' : '[xpel] verification code ' . $code . '. Do not tell others the verification code.';
        $obj = international_sms_send($ext, $phone_number, $content);
    }
    $model = new SmsCode();
    $model->ip = request()->ip();
    $model->ext = $ext;
    $model->phone = $phone;
    $model->type = $type;
    $model->code = $code;
    $model->status = 0;
    $model->save();
    $params = [
        'ext' => $ext,
        'mobile' => $mobile,
        'content' => $content,
        'res' => @$obj['data'],
    ];
    $alogs = alogs('短信', '短信验证码', $model->id, $params, $model);

    if (@$obj['status'] == 'SUCCESS') {
        return [
            'status' => 'SUCCESS',
            'msg' => '成功！',
        ];
    } else {
        return [
            'status' => false,
            'msg' => @$obj['msg'],
        ];
    }
}

function checkSmsCode($phone, $type, $code, $ext = '+86')
{
    $model = SmsCode::where([
        'phone' => $phone,
        'type' => $type,
    ])->orderByDesc('created_at')->first();
    $code = trim($code);
    if (empty($model->code) || empty($code)) {
        return ['status' => false, 'msg' => '验证码不存在！', 'error_code' => 4001];
    }
    if ('a' . $model->code !== 'a' . $code) {
        return ['status' => false, 'msg' => '验证码不正确！', 'error_code' => 4002];
    }
    if ($model->created_at->timestamp < (time() - 3000)) {
        return ['status' => false, 'msg' => '验证码已过期！', 'error_code' => 4003];
    }
    if ($model->status != 0) {
        return ['status' => false, 'msg' => '验证码已失效！', 'error_code' => 4004];
    }
    $model->status = 1;
    $model->save();
    return ['status' => 'SUCCESS', 'msg' => '验证通过！', 'error_code' => 0];
}
/*
 * 判断Rolls是否已安装*/
function tRno($roll_number)
{
    $w = DB::table('warranty_to_vehicle_coverage as wvc')
        ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
        ->where('wvc.roll_number', $roll_number)
        ->whereNull('w.deleted_at')
        ->get();
    if (count($w)) {
        return true;
    }
    $p = DB::table('precut as p')
        ->leftJoin('precut_to_vehicle_coverage as pvc', 'pvc.precut_kit_sale_id', 'p.id')
        ->where('roll_number', $roll_number)
        ->whereNull('p.deleted_at')
        // ->where('p.status', '!=', 1)
        ->select('pvc.roll_number', 'pvc.length', 'p.created_by')
        ->get();
    if (count($p)) {
        return true;
    }

    return false;
}
function tRid($id)
{
    $model = RollMaster::findOrFail($id);
    $w = DB::table('warranty_to_vehicle_coverage as wvc')
        ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
        ->where('wvc.roll_number', $model->roll_number)
        ->whereNull('w.deleted_at')
        ->get();
    if (count($w)) {
        return true;
    }
    $p = DB::table('precut as p')
        ->leftJoin('precut_to_vehicle_coverage as pvc', 'pvc.precut_kit_sale_id', 'p.id')
        ->where('roll_number', $model->roll_number)
        ->whereNull('p.deleted_at')
        ->select('pvc.roll_number', 'pvc.length', 'p.created_by')
        ->get();
    if (count($p)) {
        return true;
    }
    return false;
}

/*
 * 判断控制器与方法是否与数据库存储的一致*/
function checkAuthorityV1($level = 1)
{
    $user_id = session('admin.id');
    $user_type = session('admin.user_type');
    if ($user_type == 1) {
        return true;
    }
    if ($user_type > 3) {
        $roles = Roles::find($user_type);
        $method = request()->method();
        [$controller, $method] = explode('@', request()->route()->getActionName(), 2);
        $admin = 'App\Http\Controllers\Admin\\';
        if (strpos($controller, $admin) === 0) {
            $controller = substr($controller, strlen($admin));
            $allows = $roles->permissions()->get(['id', 'controller', 'methods']);
            if ($controller == 'AdminController') {
                foreach ($allows as $v) {
                    $ams = explode(',', $v->methods); // 方法
                    $acs = explode(',', $v->controller); // 控制器
                    foreach ($acs as $ack) {
                        if (trim($ack) == $controller) {
                            foreach ($ams as $amk) {
                                if (trim($amk) == $method) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if ($user_type == 1) {
        return true;
    }
    return false;
}

/*
 * 权限判断*/
function checkAuthorityV2($right)
{
    $admin_id = session('admin.id');
    $user_type = session('admin.user_type');
    $unique_id = session('admin.unique_id');
    if (empty($right)) {
        return true;
    }
    if ($right == 'warranty_create') {
        if ($user_type == 2) {
            if (!in_array($unique_id, ['CN00036', 'CN00037', 'CN00028'])) {
                return abort(403);
            }
        }
    }
    if ($user_type == 1) {
        return true;
    }
    return abort(403);
}

/*
 * 判断用户是否可以以普通方式新增质保*/
function cWPC()
{
    $user_type = session('admin.user_type');
    $unique_id = session('admin.unique_id');
    if (session('admin.warranty_create') != 1) {
        return false;
    }
    return true;
    $admin_id = session('admin.id');
    $user_type = session('admin.user_type');
    $unique_id = session('admin.unique_id');
    if ($user_type == 1) {
        return true;
    }
    if ($user_type > 3) {
        return checkMethodsAuthorityV1('warranty_create');
    }
    if (in_array($unique_id, ['CN00036', 'CN00037', 'CN00028'])) {
        return true;
    }
    return false;
}

/*
 * 获取剩余长度/可使用长度
 * 可使用长度不超过整体剩余长度*/

function getRlenV400($roll_number, $user_id = 1)
{
    $roll = getRollsMasterByRollNumber($roll_number);
    $rs = RollSales::where('roll_id', $roll->id)->get();
    if ($user_id == 1) {
        $length = $roll->length;
    } else {
        $length = 0;
    }
    foreach ($rs as $k => $v) {
        /*出售方*/
        if ($v->sold_by_user_id == $user_id) {
            $length -= $v->length;
        }
        /*
         * 获得方*/
        if ($v->sold_to_user_id == $user_id) {
            $length += $v->length;
        }
    }

    $len1 = DB::table('warranty_to_vehicle_coverage as tvc')
        ->leftJoin('warranty as w', 'w.id', 'tvc.warranty_id')
        ->where('tvc.roll_number', $roll_number)
        ->where('w.approved', '!=', 3)
        ->where('w.id', '>=', 1)
        ->where('w.user_id', $user_id)
        ->whereNull('tvc.deleted_at')
        ->sum('length');
    $len2 = DB::table('precut_to_vehicle_coverage as tvc')
        ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
        ->leftJoin('warranty as w', 'w.pre_id', 'p.id')
        ->whereNull('w.id')
        ->where('tvc.roll_number', $roll_number)
        ->where('p.id', '>=', 1)
        ->where('p.created_by', $user_id)
        ->whereNull('tvc.deleted_at')
        ->sum('length');
    $len1 = $len1 > 0 ? $len1 : 0;
    $len2 = $len2 > 0 ? $len2 : 0;

    $len = $length - ($len1 + $len2);
    $len = (int) $len;
    $len = $len > 0 ? $len : 0;
    return $len;
}


/*
 * 质保审核V4
 * 审核质保信息
 * 审核安装图片，数量不少于6张*/
function vWV4($id)
{
    $w = Warranty::find($id); // 获取质保
    if (empty($w->id)) {
        $msg[] = "质保不存在！";
        return $msg;
    }
    $f = [
        'user_id' => '装贴门店',
        'first_name' => '车主姓名',
        'phone_number' => '联系电话',
        'email_address' => '电子邮件',

        'region_id' => '区域',
        'province_id' => '省份',
        'city' => '城市',
        'address' => '车主地址',

        'year_id' => '车辆年份',
        'make_id' => '车辆品牌',
        'model_id' => '车辆型号',
        # 'license_plate' => '牌照号',
        'vin_number' => '车架号',

        'installer_name' => '装贴技师',
        'installation_date' => '装贴日期',
        'installation_price' => '装贴价格',
    ];
    $res = [];
    $msg = [];
    $wvs = [];
    foreach ($f as $k => $v) {
        $kk = trim($w->$k);
        if (empty($kk)) {
            $msg[] = $v . ' 不能为空！';
        }
    }
    if (!empty($w->user_id)) {
        $qudao_user = getUser($w->user_id);
        if (!$qudao_user || !$qudao_user->id) {
            $msg[] = "装贴门店 不存在：id" . $w->user_id;
        } else if ($qudao_user->trashed()) {
            $msg[] = "装贴门店 已被禁用：" . $qudao_user->abbr;
        } elseif ($qudao_user->status != 1) {
            $msg[] = "装贴门店 已被停用：" . $qudao_user->abbr;
        } else {
            if (!checkDealerBelongs($w->user_id)) {
                $msg[] = '装贴门店非下属门店，请确认：' . $qudao_user->abbr;
            }
        }
    }

    if (empty($w->precut_id)) {
        // $images = DB::table('warranty_image')->where('warranty_id', $w->id)->count('id');
        $images = WarrantyImage::where('warranty_id', $w->id)->count('id');
        if ($images >= 6 && $images <= 12) {
        } else {
            $msg[] = '安装图片保证清晰且最多12张，最少6张！';
        }
        if ($w->email_address && !pregV1('email_address', $w->email_address)) {
            $msg[] = '邮箱格式 格式不符合规范：' . $w->email_address;
        }
    }

    if (@$w->extension == '+86') {
        if (empty($w->precut_id)) {
            if ($w->license_plate && !pregV1('license_plate', $w->license_plate)) {
                $msg[] = '牌照号 格式不符合规范：' . $w->license_plate;
            }
        }
        if ($w->phone_number && (strlen($w->phone_number) < 10 || strlen($w->phone_number) > 12)) {
            $msg[] = '联系电话 格式不符合规范：' . $w->phone_number;
        }
        # $msg[] = 'extension：' . pregV1('phone_number', $w->phone_number);
    }
    if ($w->vin_number && !pregV1('vin_number', $w->vin_number)) {
        $msg[] = '车架号 格式不符合规范：' . $w->vin_number;
    }

    if (empty($w->warranty_id)) {
        $w->warranty_id = makeWarrantyId($w->installation_date);
        $w->save(); // 需要保存数据
    }
    if (empty($w->pre_id) && empty($w->precut_id)) {
        $wv = DB::table('warranty_to_vehicle_coverage')
            ->where('warranty_id', $w->id)
            ->whereNull('deleted_at')
            ->get(['part_id', 'length', 'roll_number']); // 获取卷号
        checkPartItemsV3($wv, $w->user_id, $msg);
    } else {
        /*$pre = Precut::find($w->pre_id);
        if (empty($pre)) {
            $msg[] = '专车专用套件不存在！';
        } else {
            if ($pre->user_id != $w->user_id) {
                $msg[] = '专车专用套件与装贴门店不匹配！';
            }
        }*/
        $pre = NewPrecut::find($w->precut_id);
        if (empty($pre)) {
            $msg[] = '专车专用套件不存在！';
        } else {
            if ($pre->user_id != $w->user_id) {
                $msg[] = '专车专用套件与装贴门店不匹配！';
            }
        }
    }
    if (!empty($msg)) {
        $msgModel = new WarrantyMsg();
        $msgModel->content = json_encode($msg);
        $msgModel->warranty_id = $w->id;
        $msgModel->status = 0;
        $msgModel->save();
    } else {
        $msgModel = new WarrantyMsg();
        $msgModel->content = json_encode([]);
        $msgModel->warranty_id = $w->id;
        $msgModel->status = 0;
        $msgModel->save();
    }
    return $msg;
}

function vWV5($id)
{
    $w = Warranty::find($id); // 获取质保
    if (empty($w->id)) {
        $msg[] = "质保不存在！";
        return $msg;
    }
    $f = [
        'user_id' => '装贴门店',
        'first_name' => '车主姓名',
        'phone_number' => '联系电话',
        'email_address' => '电子邮件',

        'region_id' => '区域',
        'province_id' => '省份',
        'city' => '城市',
        'address' => '车主地址',

        'year_id' => '车辆年份',
        'make_id' => '车辆品牌',
        # 'license_plate' => '牌照号',
        'vin_number' => '车架号',

        'installer_name' => '装贴技师',
        'installation_date' => '装贴日期',
        'installation_price' => '装贴价格',
    ];
    $res = [];
    $msg = [];
    $wvs = [];
    foreach ($f as $k => $v) {
        $kk = trim($w->$k);
        if (empty($kk)) {
            $msg[] = $v . ' 不能为空！';
        }
    }
    if (!empty($w->user_id)) {
        $qudao_user = getUser($w->user_id);
        if (empty($qudao_user->id)) {
            $msg[] = "装贴门店 不存在：";
        } else if ($qudao_user->trashed()) {
            $msg[] = "装贴门店 已被禁用：" . $qudao_user->abbr;
        } elseif ($qudao_user->status != 1) {
            $msg[] = "装贴门店 已被停用：" . $qudao_user->abbr;
        }
    }

    if (empty($w->precut_id)) {
        // $images = DB::table('warranty_image')->where('warranty_id', $w->id)->count('id');
        $images = WarrantyImage::where('warranty_id', $w->id)->count('id');
        if ($images >= 6 && $images <= 12) {
        } else {
            $msg[] = '安装图片保证清晰且最多12张，最少6张！';
        }
        if ($w->email_address && !pregV1('email_address', $w->email_address)) {
            $msg[] = '邮箱格式 格式不符合规范：' . $w->email_address;
        }
    }

    if (@$w->extension == '+86') {
        if (empty($w->precut_id)) {
            if ($w->license_plate && !pregV1('license_plate', $w->license_plate)) {
                $msg[] = '牌照号 格式不符合规范：' . $w->license_plate;
            }
        }
        if ($w->phone_number && (strlen($w->phone_number) < 10 || strlen($w->phone_number) > 12)) {
            $msg[] = '联系电话 格式不符合规范：' . $w->phone_number;
        }
        # $msg[] = 'extension：' . pregV1('phone_number', $w->phone_number);
    }
    if ($w->vin_number && !pregV1('vin_number', $w->vin_number)) {
        $msg[] = '车架号 格式不符合规范：' . $w->vin_number;
    }

    if (empty($w->warranty_id)) {
        $w->warranty_id = makeWarrantyId($w->installation_date);
        $w->save(); // 需要保存数据
    }
    if (empty($w->pre_id) && empty($w->precut_id)) {
        $wv = DB::table('warranty_to_vehicle_coverage')
            ->where('warranty_id', $w->id)
            ->whereNull('deleted_at')
            ->get(['part_id', 'length', 'roll_number']); // 获取卷号
        checkPartItemsV3($wv, $w->user_id, $msg);
    } else {
        $pre = NewPrecut::find($w->precut_id);
        if (empty($pre)) {
            $msg[] = '专车专用套件不存在！';
        } else {
            if ($pre->user_id != $w->user_id) {
                $msg[] = '专车专用套件与装贴门店不匹配！';
            }
        }
    }
    return $msg;
}

function modelDiff($model, $array, $fields)
{
    $diff = [];
    foreach ($fields as $k => $v) {
        if (@$model->$v == @$array[$v]) {
            continue;
        } else {
            $diff[] = [
                'label' => $v,
                'old' => @$model->$v,
                'new' => @$array[$v],
            ];
        }
    }
    return $diff;
}
/*
 * 判断质保是否一致*/
function modelDiffW($model, $array, $fields)
{
    $diff = [];
    foreach ($fields as $k => $v) {
        if (@$model->$v == @$array[$v]) {
            continue;
        } else {
            $diff[] = [
                'label' => $v,
                'old' => @$model->$v,
                'new' => @$array[$v],
            ];
        }
    }
    return $diff;
}

/*
 * 判断质保图片与浏览器传入是否一致*/
function wiDiff($model)
{
    $imags = WarrantyImage::where('warranty_id', $model->id)->get('image_src');
    $uimgs = request()->input('images');
    if (!is_array($uimgs)) {
        $uimgs = [];
    }
    $diff = [];
    foreach ($imags as $key => $value) {
        $asi = array_search($value->image_src, $uimgs);
        if ($asi === false) {
            $diff[] = [
                'label' => '安装图片',
                'old' => $value->image_src,
                'new' => '',
            ];
        } else {
            array_splice($uimgs, $asi, 1);
        }
    }
    foreach ($uimgs as $k => $v) {
        $diff[] = [
            'label' => '安装图片',
            'old' => '',
            'new' => $v,
        ];
    }
    return $diff;
}
/*
 * 判断装贴部位、膜卷、长度是否一致*/
function wcDiff($model)
{
    $udts = wazbw();
    $cs = DB::table('warranty_to_vehicle_coverage')
        ->whereNull('deleted_at')
        ->where('warranty_id', $model->id)
        ->get();
    $old = $new = [];
    foreach ($cs as $k => $v) {
        $old[] = $v->part_id . '###' . $v->roll_number . '###' . $v->length;
    }
    foreach ($udts as $k => $v) {
        $new[] = $v['part_id'] . '###' . $v['roll_number'] . '###' . $v['length'];
    }
    $diff = [];
    foreach ($old as $key => $value) {
        $asi = array_search($value, $new);
        if ($asi === false) {
            $diff[] = [
                'label' => '装贴部位',
                'old' => implode(',', explode('###', $value)),
                'new' => '',
            ];
        } else {
            array_splice($new, $asi, 1);
        }
    }
    foreach ($new as $k => $v) {
        $diff[] = [
            'label' => '装贴部位',
            'old' => '',
            'new' => implode(',', explode('###', $v)),
        ];
    }
    return $diff;
}

/*
 * 获取质保用料长度*/
function gWRL($id)
{
    $sum = WarrantyToVehicleCoverage::where('warranty_id', $id)
        ->whereNull()
        ->sum('length');
    return $sum ?: 0;
}

/*
 * 获取质保历史变更记录*/
function getWSH($id)
{
    $datas = DB::table('warranty_logs as wl')
        ->leftJoin('users as u', 'u.id', 'wl.created_by')
        ->where('wl.warranty_id', $id)
        ->orderByDesc('wl.id')
        ->get(['wl.id', 'wl.status', 'u.abbr', 'wl.created_at', 'wl.created_by', 'wl.note']);
    return $datas;
}


/*
 * 质保审核V3
 * 审核质保信息
 * 审核安装图片，数量不少于6张*/
function checkWarrantyV4($id)
{
    $w = Warranty::findOrFail($id); // 获取质保
    $f = [
        'user_id' => '装贴门店',
        'first_name' => '车主姓名',
        'phone_number' => '联系电话',
        'email_address' => '电子邮件',

        'region_id' => '区域',
        'province_id' => '省份',
        'city' => '城市',
        'address' => '车主地址',

        'year_id' => '车辆年份',
        'make_id' => '车辆品牌',
        'model_id' => '车辆型号',
        'license_plate' => '牌照号',
        'vin_number' => '车架号',

        'installer_name' => '装贴技师',
        'installation_date' => '装贴日期',
        'installation_price' => '装贴价格',
    ];
    $res = [];
    $msg = [];
    $wvs = [];
    foreach ($f as $k => $v) {
        $kk = trim($w->$k);
        if (empty($kk)) {
            return false;
        }
    }

    // $images = DB::table('warranty_image')->where('warranty_id', $w->id)->count('id');
    $images = WarrantyImage::where('warranty_id', $w->id)->count('id');
    if ($images >= 6 && $images <= 12) {
    } else {
        return false;
    }

    if (empty($w->warranty_id)) {
        $w->warranty_id = makeWarrantyId($w->installation_date);
        $w->save(); // 需要保存数据
    }
    if (empty($w->pre_id)) {
        $wv = DB::table('warranty_to_vehicle_coverage')
            ->where('warranty_id', $w->id)
            ->whereNull('deleted_at')
            ->get(['part_id', 'length', 'roll_number']); // 获取卷号
        checkPartItemsV3($wv, $w->user_id, $msg);
    } else {
        $pre = Precut::find($w->pre_id);
        if (empty($pre)) {
            return false;
        } else {
            if ($pre->user_id != $w->user_id) {
                return false;
            }
        }
    }


    /*
     * foreach ($wv as $k => $v) {
                minusRestlen($w->user_id, $v->roll_number, $v->length); // 发起审核时更新剩余长度
            }*/
    return true;
}


/*
 * 判断邮箱格式
 * 邮箱为空时返回为真*/
function cEmail($email)
{
    $preg = '/^\w{1,}@\w{1,}\.\w{1,}$/';
    if (empty($email)) {
        return true;
    }
    if (!preg_match($preg, $email)) {
        return false;
    }
    $e = explode('@', $email);
    if ($e[count($e) - 1] == 'qq.co') {
        return false;
    }
    return true;
}

/*
 * 正则表达式判断*/
function pregV1($column, $value)
{
    $value = trim($value);
    $email = '/^\w{1,}@\S{1,}\.\w{1,}$/';
    # $license_plate = "/^(([京津沪渝蒙新藏宁桂黑吉辽晋冀青鲁豫苏皖浙闽赣湘鄂粤琼甘陕贵云川港澳台]{1}[A-Z]{1})[-]?|([wW][Jj][京津沪渝蒙新藏宁桂黑吉辽晋冀青鲁豫苏皖浙闽赣湘鄂粤琼甘陕贵云川港澳台]{1}[-]?)|([a-zA-Z]{2}))([A-Za-z0-9]{5}|[DdFf][A-HJ-NP-Za-hj-np-z0-9][0-9]{4}|[0-9]{5}[DdFf])$/u";
    # $license_plate = "/^[京津沪渝蒙新藏宁桂黑吉辽晋冀青鲁豫苏皖浙闽赣湘鄂粤琼甘陕贵云川港澳台]{1}[A-Z]{1}[A-Z0-9]{5}[DF]{0,1}$/u";
    $license_plate = "/^[京津沪渝蒙新藏宁桂黑吉辽晋冀青鲁豫苏皖浙闽赣湘鄂粤琼甘陕贵云川港澳台]{1}[A-Z]{1}[A-Z0-9]{5,6}$/u";
    $vin_number = '/^[A-Z0-9]{9,18}$/';
    $phone = '/^1[1-9]\d{9}$/';
    $value = trim($value);

    if ($column == 'email_address') {
        if (!preg_match($email, $value)) {
            return false;
        }
    }

    if ($column == 'email') {
        if (!preg_match($email, $value)) {
            return false;
        }
        $e = explode('@', $email);
        if ($e[count($e) - 1] == 'qq.co') {
            return false;
        }
    }
    if ($column == 'vin_number') {
        $value = strtoupper($value);
        if (!preg_match($vin_number, $value)) {
            return false;
        }
    }
    if ($column == 'license_plate') {
        $value = strtoupper($value);
        if (!preg_match($license_plate, $value)) {
            return false;
        }
    }
    if ($column == 'phone' || $column == 'phone_number') {
        if (!preg_match($phone, $value)) {
            return false;
        }
    }
    return true;
}

function uWMR($roll_number)
{
    $roll = getRollsMasterByRollNumber($roll_number);
    if (empty($roll->id)) {
        return false;
    }
    if (!empty($roll->deleted_at)) {
        return false;
    }
    DB::table('warranty_to_vehicle_coverage as wvc')
        ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
        ->whereNull('wvc.deleted_at')
        ->where('wvc.roll_number', $roll_number);
}

/*
 * 根据浏览器传入信息
 * 判断质保信息是否有修改*/
function wDiff1($model)
{
    $diff = [];
    $array = request()->input();
    $fields = [];
    $f1 = [
        'first_name' => '车主姓名',
        'extension' => '地区号',
        'phone_number' => '联系电话',
        'email_address' => '电子邮件',
        'address' => '车主地址',
        'license_plate' => '牌照号',
        'vin_number' => '车架号',
        'installer_name' => '装贴技师',
        'installation_price' => '车主姓名',
        'additional_comments' => '车主姓名',
    ];
    $f2 = [
        'user_id' => '装贴门店',
        'region_id' => '区域',
        'province_id' => '省',
        'city' => '城市',
        'year_id' => '车辆年份',
        'make_id' => '车辆品牌',
        'model_id' => '车辆型号',
    ];
    $f3 = [
        'installation_date' => '装贴日期',
    ];
    foreach ($f1 as $k => $v) {
        $new = trim(request()->input($k));
        $old = $model->$k;
        if ($new != $old) {
            $diff[] = [
                'label' => $v,
                'old' => $old,
                'new' => $new,
            ];
        }
    }
    foreach ($f2 as $k => $v) {
        $new = (int) trim(request()->input($k));
        $old = $model->$k;
        if ($new != $old) {
            $diff[] = [
                'label' => $v,
                'old' => $old,
                'new' => $new,
            ];
        }
    }
    foreach ($f3 as $k => $v) {
        $value = strtotime(request()->input($k));
        $new = date('Y-m-d', $value);
        $old = date('Y-m-d', strtotime($model->$k));
        if ($new != $old) {
            $diff[] = [
                'label' => $v,
                'old' => $old,
                'new' => $new,
            ];
        }
    }
    $wiDiff = wiDiff($model);
    $wcDiff = wcDiff($model);
    $diff = array_merge($diff, $wiDiff, $wcDiff);
    return $diff;
}
/*
 * 更新质保信息*/
function wSave($model)
{
    $admin_id = session('admin.id');
    $fields = [
        'first_name' => '车主姓名',
        'extension' => '地区号',
        'phone_number' => '联系电话',
        'email_address' => '电子邮件',
        'address' => '车主地址',
        'license_plate' => '牌照号',
        'vin_number' => '车架号',
        'installer_name' => '装贴技师',
        'installation_price' => '车主姓名',
        'additional_comments' => '车主姓名',
    ];
    $f2 = [
        'user_id' => '装贴门店',
        'region_id' => '区域',
        'province_id' => '省',
        'city' => '城市',
        'year_id' => '车辆年份',
        'make_id' => '车辆品牌',
        'model_id' => '车辆型号',
        'precut_id' => '专车专用套件ID',
    ];
    $f3 = [
        'installation_date' => '装贴日期',
    ];
    foreach ($fields as $k => $v) {
        $value = trim(request()->input($k));
        $model->$k = $value;
    }
    foreach ($f2 as $k => $v) {
        $value = (int) trim(request()->input($k));
        $model->$k = $value;
    }
    foreach ($f3 as $k => $v) {
        $value = strtotime(request()->input($k));
        if ($value <= 0) {
            $value = null;
        } else {
            $value = date('Y-m-d H:i:s', $value);
        }
        $model->$k = $value;
    }
    if (empty($model->warranty_id)) {
        $model->warranty_id = makeWarrantyId($model->installation_date);
    }
    return $model;
}

/*
 * 更新质保图片*/
function rwI($model)
{
    $dtime = gDate();
    $imgs = [];
    $bool = false;
    $rmg = request()->input('images');
    if (!empty($rmg) && is_array($rmg)) {
        foreach ($rmg as $k => $v) {
            $item = [];
            $item['warranty_id'] = $model->id;
            $item['created_at'] = $dtime;
            $item['updated_at'] = $dtime;
            $item['image_src'] = $v;
            $item['part_id'] = $k + 1;
            $imgs[] = $item;
        }
    }
    if (!empty($imgs)) {
        DB::table('warranty_image')->where('warranty_id', $model->id)->delete();
        $bool = DB::table('warranty_image')->insert($imgs);
    }
    return $bool;
}

function rwI1($model)
{
    $dtime = gDate();
    $imgs = [];
    $bool = false;
    $rmg = request()->input('images');
    $rmg = explode(",", $rmg);
    if (!empty($rmg) && is_array($rmg)) {
        foreach ($rmg as $k => $v) {
            $item = [];
            $item['warranty_id'] = $model->id;
            $item['created_at'] = $dtime;
            $item['updated_at'] = $dtime;
            $item['image_src'] = $v;
            $item['part_id'] = $k + 1;
            $imgs[] = $item;
        }
    }
    if (!empty($imgs)) {
        DB::table('warranty_image')->where('warranty_id', $model->id)->delete();
        $bool = DB::table('warranty_image')->insert($imgs);
    }
    return $bool;
}

/*
 * 更新质保装贴部位*/
function rwC($model)
{
    $dtime = gDate();
    $udts = wazbw();
    $uploads = [];
    $bool = false;
    foreach ($udts as $k => $v) {
        Log::channel('wlog')->info('roll_number' . $v['roll_number'] . 'film_type_id' . $v['film_type_id']);
        $filmType = FilmTypeMaster::where('id', $v['film_type_id'])->first();
        if (!empty($filmType) && !empty($filmType->warranty_days)) {
            $starTime = $model->installation_date ? strtotime($model->installation_date) : time();
            $endTime = strtotime("+$filmType->warranty_days days", $starTime);
            $v['start_time'] = $starTime;
            $v['end_time'] = $endTime;
        } else {
            $v['start_time'] = "";
            $v['end_time'] = "";
        }
        $v['warranty_id'] = $model->id;
        $v['created_at'] = $dtime;
        $v['updated_at'] = $dtime;
        $uploads[] = $v;
    }
    // 删除卷膜
    if (!empty($uploads)) {
        //$bool = WarrantyToVehicleCoverage::where('warranty_id', $model->id)->delete();
        DB::table('warranty_to_vehicle_coverage')
            ->where('created_at', '<',$dtime)
            ->where('warranty_id', $model->id)
            ->limit(count($uploads) * 2)
            ->delete();
        $bool = DB::table('warranty_to_vehicle_coverage')->insert($uploads);
    }
    return $bool;
}


/*
 * 根据卷号更新剩余长度
 * 1.卷号不存在，软删除所有销售记录
 * 2.卷号不存在，将restlen设置为0
 * 3.卷号不存在，但是质保存在，不处理 =》 软删除
 * 4.卷号不存在，专车专用套件，不处理 =》 软删除
 * 5.卷号存在，获取专车专用使用长度，无论是否安装
 * 6.卷号存在，获取质保使用长度，仅通过未删除、质保未删除、记录未删除*/


/*
 * 获取卷号剩余总长度
 * 卷号不存在或已删除，返回0
 * 查询质保使用记录
 * 查询专车专用套件使用记录
 * 总长度减去两者
 * */
function getRestlenV301($roll_number)
{
    $restlen = RollRestlen::where('roll_number', $roll_number)
        ->sum('restlen');
    return @$restlen ?: 0;
}
function getRestlenV3($roll_number)
{
    $roll = getRollsMasterByRollNumber($roll_number);
    if (empty($roll->id) || !empty($roll->deleted_at)) {
        return 0;
    }
    $len1 = DB::table('warranty_to_vehicle_coverage as tvc')
        ->leftJoin('warranty as w', 'w.id', 'tvc.warranty_id')
        ->where('tvc.roll_number', $roll_number)
        ->where(function ($query) {
            $query->where('w.approved', '!=', 3)
                ->orWhere('w.pre_id', '>=', 1);
        })
        ->where('w.id', '>=', 1)
        ->whereNull('tvc.deleted_at')
        ->whereNull('w.deleted_at')
        ->sum('length');
    $len2 = DB::table('precut_to_vehicle_coverage as tvc')
        ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
        ->where('tvc.roll_number', $roll_number)
        ->where('p.id', '>=', 1)
        ->whereNull('p.deleted_at')
        ->whereNull('tvc.deleted_at')
        ->where('p.status', '!=', 1)
        ->sum('length');
    $len1 = $len1 > 0 ? $len1 : 0;
    $len2 = $len2 > 0 ? $len2 : 0;
    $len = $roll->length - ($len1 + $len2);
    $len = (int) $len;
    $len = $len > 0 ? $len : 0;
    return $len;
}

/*
 * 判断卷是否分配*/

/*
 * 传入卷号、用户ID
 * 获取用户可分配长度
 * 获取用户可使用长度
 * 可分配长度不超过总长度
 * 可分配长度不超过剩余总长度
 * 不存在或已删除卷号长度返回0
 * 查询调货记录，如果有则减去长度未审核项，则减去长度
 * 查询退货记录，如果有未审核项，则长度返回0
 * 对于质保，查询已通过或使用套件，且未删除数据
 * 对于专车专用套件，查询未分配，以status为准
 * 质保更新时，同步更新专车专用套件状态*/
function getRlenV401($roll_number, $user_id = 1)
{
    $rr = RollRestlen::where('roll_number', $roll_number)
        ->where('user_id', $user_id)
        ->first();
    return @$rr->restlen ?: 0;
}
function getRlenV401V1($roll_number, $user_id = 1)
{
    $roll = getRollsMasterByRollNumber($roll_number);
    if (empty($roll->id) || !empty($roll->deleted_at)) {
        return 0;
    }
    $rt = RollReturn::where('user_id', $user_id)
        ->where('status', 0)
        ->first();
    if (!empty($rt->id)) {
        return 0;
    }

    $rs = RollSales::where('roll_id', $roll->id)->get();
    if ($user_id == 1) {
        $length = $roll->length;
    } else {
        $length = 0;
    }
    foreach ($rs as $k => $v) {
        /*出售方*/
        if ($v->sold_by_user_id == $user_id) {
            $length -= $v->length;
        }
        /*
         * 获得方*/
        if ($v->sold_to_user_id == $user_id) {
            $length += $v->length;
        }
    }
    $rtf = RollTransfer::where('transfer_by_user_id', $user_id)
        ->where('roll_id', $roll->id)
        ->where('approved', 0)
        ->sum('length');
    $rtf = $rtf > 0 ? $rtf : 0;

    /*->where('w.approved', '!=', 3)*/
    $len1 = DB::table('warranty_to_vehicle_coverage as tvc')
        ->leftJoin('warranty as w', 'w.id', 'tvc.warranty_id')
        ->where('tvc.roll_number', $roll_number)
        ->where(function ($query) {
            $query->where('w.approved', '!=', 3)
                ->orWhere('w.pre_id', '>=', 1);
        })
        ->where('w.id', '>=', 1)
        ->where('w.user_id', $user_id)
        ->whereNull('tvc.deleted_at')
        ->whereNull('w.deleted_at')
        ->sum('length');
    // 专车专用套件长度
    $len2 = 0;
    $len2 = DB::table('precut_to_vehicle_coverage as tvc')
        ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
        ->where('tvc.roll_number', $roll_number)
        ->where('p.id', '>=', 1)
        ->where('p.created_by', $user_id)
        ->whereNull('p.deleted_at')
        ->whereNull('tvc.deleted_at')
        ->where('p.status', '!=', 1)
        ->sum('length');
    /*$pv = DB::table('precut_to_vehicle_coverage as tvc')
        ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
        ->where('tvc.roll_number', $roll_number)
        ->where('p.id', '>=', 1)
        ->where('p.created_by', $user_id)
        ->whereNull('p.deleted_at')
        ->whereNull('tvc.deleted_at')
        ->select(['length', 'p.id', 'p.status'])
        ->get();
    if (count($pv)) {
        $pids = Arr::pluck($pv, 'id');
        $wpv = DB::table('warranty as w')
            ->whereNull('deleted_at')
            ->whereIn('pre_id', $pids)
            ->groupBy('w.pre_id')
            ->get(['pre_id']);
        $wpvs = Arr::pluck($wpv, 'pre_id');
        foreach ($pv as $k => $v) {
            if (!in_array($v->id, $wpvs)) {
                $len2 += $v->length;
            }
        }
    }*/
    $len1 = $len1 > 0 ? $len1 : 0;
    $len2 = $len2 > 0 ? $len2 : 0;
    $rtf = $rtf > 0 ? $rtf : 0; // 调货未审核状态下需要先扣除被调货方的长度

    $len = $length - ($len1 + $len2 + $rtf);
    $len = (int) $len;
    $len = $len > 0 ? $len : 0;
    $rlen = getRestlenV3($roll_number);
    if ($len > $rlen) {
        return $rlen;
    } else {
        return $len;
    }
    return $len;
}
/*
 * 批量获取
 * 批量获取用户剩余长度*/
function getRlens401($rnos, $user_id)
{
    $res = [];
    $rnos = array_unique($rnos);
    foreach ($rnos as $k => $v) {
        $res[$v] = getRlenV401($v, $user_id);
    }
    return $res;
}
/*
 * 批量获取
 * 批量获取卷号总剩余长度*/
function getRlens402($rnos)
{
    $res = [];
    $rnos = array_unique($rnos);
    foreach ($rnos as $k => $v) {
        $res[$v] = getRestlenV3($v);
    }
    return $res;
}

/*
 * 根据套件ID获取已通过质保记录*/
function gWP($pre_id)
{
    $model = Warranty::where('pre_id', $pre_id)
        ->where('approved', '!=', 3)
        ->first();
    return @$model;
}

/*
 * 根据卷实例获取当前拥有卷的用户
 * 卷号已确定存在
 * 已申请退货用户长度为0，申请通过后可能重新分配
 * 已申请调货，扣除发起方长度，接收方长度不增加
 * */
function getRlenV405($roll)
{
    $model = RollRestlen::where('roll_number', $roll->roll_number)
        ->where('restlen', '>', 0);
    $rest = $model->get(['user_id', 'roll_number', 'restlen']);
    return $rest;
}

function getRlenV405V2($roll)
{
    $ulen = [];
    $ulen[1] = $roll->length;
    $rt = RollReturn::where('status', 0)
        ->where('roll_id', $roll->id)
        ->get('roll_id');
    $rtids = [];
    if (count($rt)) {
        $rtids = Arr::pluck($rt, 'roll_id'); // 清楚已申请退货用户
    }

    $rs = RollSales::where('roll_id', $roll->id)->get();
    foreach ($rs as $k => $v) {
        $ulen[$v->sold_by_user_id] = @$ulen[$v->sold_by_user_id] - $v->length;
        $ulen[$v->sold_to_user_id] = @$ulen[$v->sold_to_user_id] + $v->length;
    }
    $rtf = RollTransfer::where('roll_id', $roll->id)
        ->where('approved', 0)
        ->get(['transfer_by_user_id', 'transfer_to_user_id', 'note']);
    foreach ($rtf as $k => $v) {
        $ulen[$v->transfer_by_user_id] = @$ulen[$v->transfer_by_user_id] - $v->length;
    }

    $wvc = DB::table('warranty_to_vehicle_coverage as tvc')
        ->leftJoin('warranty as w', 'w.id', 'tvc.warranty_id')
        ->where('tvc.roll_number', $roll->roll_number)
        ->where('w.approved', '!=', 3)
        ->where('w.id', '>=', 1)
        ->whereNull('tvc.deleted_at')
        ->whereNull('w.deleted_at')
        ->get(['tvc.length', 'w.user_id', 'w.pre_id']);
    $pud = [];
    $pus = []; //  用户
    foreach ($wvc as $k => $v) {
        if ($v->pre_id) {
            $pud[$v->pre_id] = @$pud[$v->pre_id] + $v->length; // 套件暂存长度
            $pus[$v->pre_id] = $v->user_id; // 不考虑一套多用
        } else {
            $ulen[$v->user_id] = @$ulen[$v->user_id] - $v->length;
        }
    }
    // 专车专用套件长度
    $len2 = 0;
    $pvc = DB::table('precut_to_vehicle_coverage as tvc')
        ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
        ->where('tvc.roll_number', $roll->roll_number)
        ->where('p.id', '>=', 1)
        ->whereNull('p.deleted_at')
        ->whereNull('tvc.deleted_at')
        ->get(['tvc.length', 'p.created_by', 'p.id', 'p.user_id']);

    foreach ($pvc as $k => $v) {
        $pud[$v->id] = 0; // 如果存在则减去
        $ulen[$v->created_by] = @$ulen[$v->created_by] - $v->length;
    }
    foreach ($pud as $k => $v) {
        if ($v > 0) {
            $uid = @$pus[$k];
            $ulen[$uid] = @$ulen[$uid] - $v;
        }
    }
    $rest = [];
    foreach ($ulen as $k => $v) {
        if ($v > 0 && !in_array($k, $rtids)) {
            $rest[] = $k;
        }
    }
    return $rest;
}

/*
 * 获取省代下属卷号剩余总长度
 * 卷号已确定存在*/
function getRlenV403($roll_models, $user_id = 1)
{
    return [];
    $rids = Arr::pluck($roll_models, 'id');
    $rns = Arr::pluck($roll_models, 'roll_number');
    $rt = RollReturn::where('user_id', $user_id)
        ->where('status', 0)
        ->whereIn('roll_id', $rids)
        ->get('roll_id');
    $rtids = [];
    if (count($rt)) {
        $rtids = Arr::pluck($rt, 'roll_id');
    }
    $rs = RollSales::whereIn('roll_id', $rids)
        ->get();


    $rs = RollSales::where('roll_id', $roll->id)->get();
    if ($user_id == 1) {
        $length = $roll->length;
    } else {
        $length = 0;
    }
    foreach ($rs as $k => $v) {
        /*出售方*/
        if ($v->sold_by_user_id == $user_id) {
            $length -= $v->length;
        }
        /*
         * 获得方*/
        if ($v->sold_to_user_id == $user_id) {
            $length += $v->length;
        }
    }
    $rtf = RollTransfer::where('transfer_by_user_id', $user_id)
        ->where('roll_id', $roll->id)
        ->where('approved', 0)
        ->sum('length');
    $rtf = $rtf > 0 ? $rtf : 0;

    /*->where('w.approved', '!=', 3)*/
    $len1 = DB::table('warranty_to_vehicle_coverage as tvc')
        ->leftJoin('warranty as w', 'w.id', 'tvc.warranty_id')
        ->where('tvc.roll_number', $roll_number)
        ->where(function ($query) {
            $query->where('w.approved', '!=', 3)
                ->orWhere('w.pre_id', '>=', 1);
        })
        ->where('w.id', '>=', 1)
        ->where('w.user_id', $user_id)
        ->whereNull('tvc.deleted_at')
        ->whereNull('w.deleted_at')
        ->sum('length');
    // 专车专用套件长度
    $len2 = 0;
    $len2 = DB::table('precut_to_vehicle_coverage as tvc')
        ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
        ->where('tvc.roll_number', $roll_number)
        ->where('p.id', '>=', 1)
        ->where('p.created_by', $user_id)
        ->whereNull('p.deleted_at')
        ->whereNull('tvc.deleted_at')
        ->where('p.status', '!=', 1)
        ->sum('length');
    /*$pv = DB::table('precut_to_vehicle_coverage as tvc')
        ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
        ->where('tvc.roll_number', $roll_number)
        ->where('p.id', '>=', 1)
        ->where('p.created_by', $user_id)
        ->whereNull('p.deleted_at')
        ->whereNull('tvc.deleted_at')
        ->select(['length', 'p.id', 'p.status'])
        ->get();
    if (count($pv)) {
        $pids = Arr::pluck($pv, 'id');
        $wpv = DB::table('warranty as w')
            ->whereNull('deleted_at')
            ->whereIn('pre_id', $pids)
            ->groupBy('w.pre_id')
            ->get(['pre_id']);
        $wpvs = Arr::pluck($wpv, 'pre_id');
        foreach ($pv as $k => $v) {
            if (!in_array($v->id, $wpvs)) {
                $len2 += $v->length;
            }
        }
    }*/
    $len1 = $len1 > 0 ? $len1 : 0;
    $len2 = $len2 > 0 ? $len2 : 0;
    $rtf = $rtf > 0 ? $rtf : 0; // 调货未审核状态下需要先扣除被调货方的长度

    $len = $length - ($len1 + $len2 + $rtf);
    $len = (int) $len;
    $len = $len > 0 ? $len : 0;
    $rlen = getRestlenV3($roll_number);
    if ($len > $rlen) {
        return $rlen;
    } else {
        return $len;
    }
    return $len;
}

/*
 * 根据模型号返回产品ID*/
function getFTMPid($film_type_id)
{
    $model = FilmTypeMaster::find($film_type_id);
    return @$model->product_type_id ?: 1;
}

function Refresh()
{
    $admin_id = session('admin.id');
    $admin = Admin::find($admin_id);
    if (empty($admin->id)) {
        $bool = session()->forget('admin');
        $bool = session()->forget('admin_sms_check');
        return redirect('/admin/login')->with('trash', ['content' => '账户被停用，如有疑问，请联系管理员', 'type' => 'error']);
    }
    if ($admin->status != 1) {
        $bool = session()->forget('admin');
        $bool = session()->forget('admin_sms_check');
        return redirect('/admin/login')->with('trash', ['content' => '账户被停用，如有疑问，请联系管理员', 'type' => 'error']);
    }

    session(['admin' => $admin]);
}

/*
 * 根据质保实例获取经销商名称*/
function getWDName($warranty)
{
    if (empty($warranty->dealer_name)) {
        if (empty($warranty->user_id)) {
            return '';
        }
        $admin = Admin::withTrashed()->find($warranty->user_id);
        return @$admin->abbr;
    }
    return $warranty->dealer_name;
}
/*
 * 根据质保实例获取省代名称*/
function getWDDName($warranty)
{
    if (empty($warranty->distributor_name)) {
        if (empty($warranty->user_id)) {
            return '';
        }
        $admin = Admin::withTrashed()->find($warranty->user_id);
        if ($admin->user_type == 3) {
            $user = Admin::withTrashed()->find($admin->creator_id);
            if (!empty($user->id)) {
                $admin = $user;
            }
        }
        return @$admin->abbr;
    }
    return $warranty->distributor_name;
}


/*
 * 已通过质保信息修改手机号码时，发送短信提示
 * */
function sendNotice($notice)
{
    if (empty($notice) || empty($notice['phone_number'])) {
        return [
            'status' => false,
            'msg' => '手机号码不能为空！'
        ];
    }
    $alogs = alogs('短信', '质保短信通知', $notice['id'], null, $notice);

    $ext = @$notice['extension'];
    $phone_number = @$notice['phone_number'];
    if (!in_array($ext, ['+86', '+886', '+853', '+852'])) {
        $ext = null;
    }
    if (empty($ext)) {
        return ['status' => false, 'msg' => '地区号不能为空！'];
    }
    if (empty($phone_number)) {
        return ['status' => false, 'msg' => '手机号码不能为空！'];
    }
    if ($ext == '+86') {
        $mobile = $phone_number;
        $content = '【XPEL保护膜认证店】尊敬的车主，您的质保信息发生变更，如有疑问，请联系：4006-909061';
        $obj = message_sms_send($ext, $phone_number, $content);
    } else {
        $mobile = $phone_number;
        $content = '【XPEL保护膜认证店】尊敬的客戶，您的保固資訊發生變更，請在https://www.xpel.com.tw/線上保固查詢系統確認，退訂回N';
        $obj = international_sms_send($ext, $phone_number, $content);
    }
    $params = [
        'ext' => $ext,
        'mobile' => $mobile,
        'content' => $content,
        'res' => @$obj['data'],
    ];

    $alogs->new = $params;
    $alogs->save();

    if (@$obj['status'] == 'SUCCESS') {
        return [
            'status' => 'SUCCESS',
            'msg' => '成功！',
        ];
    } else {
        return [
            'status' => false,
            'msg' => @$obj['msg'],
        ];
    }
}

/*
 * 短信发送*/




/*
 * 生成Excel
 * 自动换行*/
function makeExcel($data, $filename = null)
{
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    if (empty($data)) {
    } else {
        $header = Arr::pluck($data[0], 'label');
        $sheet->fromArray($header, NULL, 'A1');
        foreach ($data as $k => $v) {
            $value = Arr::pluck($v, 'value');
            $sheet->fromArray($value, NULL, 'A' . (2 + $k));
        }
        $length = count($data) + 1;
        $ls = range('A', 'Z');
        $nos = count($header);
        if ($nos < 26) {
            $end = 'Z';
        } else {
            $f = floor($nos);
            $f = @$ls[$f];
            $end = $f . 'Z';
        }
        $end = $end . $length;
        $spreadsheet->getActiveSheet()->getStyle('A1:' . $end)
            ->getAlignment()->setWrapText(true);
        $spreadsheet->getActiveSheet()->getStyle('A1');
        foreach (range('A', 'Z') as $columnID) {
            $spreadsheet->getActiveSheet()->getColumnDimension($columnID)
                ->setWidth(20);
        }
    }
    $filename = $filename ?: time() . '.xlsx';
    $filename = basename($filename, '.xlsx') . '.xlsx';
    $temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
    $writer->save($temp_file);
    return response()->download($temp_file, $filename);
}

/*
 * 从CN60001开始
 * 为了兼容旧数据、6位数据
 * 但id小于20000时，最大值不可以超过90000
 * 但id大于20000时，值根据unique_id获取，并查重*/
function makeUniqueId()
{
    $no = 60001;
    $cn = 'CN';
    $data = DB::table('users')
        ->where('unique_id', 'like', 'CN6%')
        ->orderByDesc('unique_id')
        // ->orderByDesc('id')
        ->first();
    if (empty($data->unique_id)) {
        return $cn . $no;
    }
    $unique_id = $data->unique_id;
    $no = (int) str_replace('CN', '', $unique_id);
    $no = $no + 1;
    $str = 'CN' . $no;
    $c = DB::table('users')
        ->where('unique_id', $str)
        ->count();
    return $str;
}

/*
 * 国际短信发送*/
/*
 *{"status":"error","code":254,"msg":"Can not match the International Phone number"}
 * {status":"success","send_id":"093c0a7df143c087d6cba9cdf0cf3738","fee":0.046,"account_balance":14197.087}
 * $ext: +886, +852, +853
*/
function international_sms_send($ext, $phone, $content)
{
    $config = [
        'appid' => '61611',
        'appkey' => '83aba62894ad6b0c2d7d54132b5fd066',
        'sign_type' => 'normal',
        'server' => 'https://api.mysubmail.com/',
    ];
    $submail = new \INTERNATIONALSMSsend($config);
    $submail->setTo($ext . $phone);
    $submail->SetContent($content);
    $xsend = $submail->send();
    if (@$xsend['status'] === 'success') {
        return [
            'status' => 'SUCCESS',
            'msg' => '发送成功！',
            'data' => $xsend,
        ];
    } else {
        return [
            'status' => false,
            'msg' => @$xsend['msg'],
            'data' => $xsend,
        ];
    }
}

/*
 * 国内短信发送*/
function message_sms_send_old($ext, $phone, $content)
{
    $k = 'cabc28e874dc0eff98f19d2d57ac9a36';
    $url = 'http://api.ljioe.cn/api/v1/sms';
    $account = 'xingyinghy';
    $timestamp = time();
    $key = md5($k . md5($timestamp));

    $params = [
        'content' => $content,
        'mobile' => $phone,
        'account' => $account,
        'code' => '',
        'ext' => '',
        'timestamp' => $timestamp,
        'key' => $key,
    ];
    $client = new  \GuzzleHttp\Client();
    $res = $client->request('post', $url, ['json' => $params]);
    $data = $res->getBody()->getContents();
    if (is_string($data)) {
        $obj = json_decode($data);
    } else {
        $obj = $data;
    }
    if (@$obj->code == 20000) {
        return [
            'status' => 'SUCCESS',
            'msg' => '发送成功！',
            'data' => $obj,
        ];
    } else {
        return [
            'status' => false,
            'msg' => @$obj->desc,
            'data' => $obj,
        ];
    }
}

function message_sms_send($ext, $phone, $content)
{
    $username = 'SHdhkjhy';
    $tKey = time();
    $password = md5(md5("Dengwho@1") . $tKey);
    $url = 'https://api-shss.zthysms.com/v2/sendSms';

    $phone = trim(str_replace("+86", '', $phone));
    $params = [
        'content' => $content,
        'mobile' => $phone,
        'username' => $username,
        'password' => $password,
        'tKey' => $tKey,
        'time' => ""
    ];
    $client = new  \GuzzleHttp\Client();
    $res = $client->request('post', $url, ['json' => $params]);
    $data = $res->getBody()->getContents();
    if (is_string($data)) {
        $data = json_decode($data);
    }
    if (@$data->code == 200) {
        return [
            'status' => 'SUCCESS',
            'msg' => '发送成功！',
            'data' => $data,
        ];
    }
    return [
        'status' => false,
        'msg' => @$data->msg,
        'data' => $data,
    ];
}

/*
 * 获取登录用户ID*/
function gui()
{
    return session('admin.id');
}
/*
 * 获取登录公司简称*/
function gua()
{
    return session('admin.abbr') ?: session('admin.company_name');
}
/*
 * 获取登录用户类型*/
function gut()
{
    return session('admin.user_type');
}
/*
 * 获取登录用户实例*/
function gum()
{
    $admin_id = gui();
    return Admin::find(session($admin_id));
}
/*
 * 生成套件ID*/
function makePrecutId($no = 1, $fids = [])
{
    // 10055685
    $model = \App\Models\Sequences::where('table', 'new_precut')
        ->first();
    if (empty($model)) {
        $model = new \App\Models\Sequences();
        $model->next = 1;
        $model->save();
    }
    $list = range($model->next, $model->next + $no - 1);
    $model->next = $model->next + $no;
    $model->save();
    $res = [];
    foreach ($list as $k => $v) {
        $kit = str_pad($v, 8, 0, STR_PAD_LEFT);
        $res[] = 'KIT' . $kit;
        # $res[] = 'KIT'.(10000000+$v);
    }
    return $res;
}
/*
 * 生成套件ID*/
function makePrecutIdV2($pvcs)
{
    $fids = Arr::pluck($pvcs, 'film_type_id');
    $ftm = FilmTypeMaster::get();
    $fms = [];
    foreach ($ftm as $k => $v) {
        $fms[$v->id] = $v->simplified_chiness_value;
    }
    $mids = [];
    $pids = [];
    foreach ($pvcs as $k => $v) {
        // $mids[$v->film_type_id] = @$mids[$v->film_type_id] + $v->number;
        $fm = @$fms[$v['film_type_id']];
        $pre = mb_substr($fm, 4, 1);
        $ids = makePrecutIdV1($v['number'], $pre);
        $pids = array_merge($pids, $ids);
    }
    return $pids;
}
function makePrecutIdV3($number)
{
    return makePrecutIdV1($number);
}

/*
 * */

function makePrecutIdV1($no = 1, $sep = null)
{
    // 10055685
    $prefix = 'T';
    $sep = strtoupper($sep);
    if (in_array($sep, ['A', 'M'])) {
        $prefix = $sep;
    }
    $table = 'new_precut_' . strtolower($prefix);
    $model = \App\Models\Sequences::where('table', $table)
        ->first();
    if (empty($model)) {
        $model = new \App\Models\Sequences();
        $model->table = $table;
        $model->next = 1;
        $model->save();
    }
    $list = range($model->next, $model->next + $no - 1);
    $model->next = $model->next + $no;
    $model->save();
    $res = [];
    foreach ($list as $k => $v) {
        $kit = str_pad($v, 8, 0, STR_PAD_LEFT);
        $res[] = $prefix . $kit;
    }
    return $res;
}

/*
 * 获取剩余最小长度实例*/
function getRRV1($film_type_id, $admin_id = null)
{
    $admin_id = (int) $admin_id ?: gui();
    $model = DB::table('roll_restlen as rr')
        ->leftJoin('roll_master as rm', 'rm.roll_number', 'rr.roll_number')
        ->where('rm.film_type_id', $film_type_id)
        ->whereNull('rm.deleted_at')
        ->whereNull('rr.deleted_at')
        ->where('rr.restlen', '>', 0)
        ->where('rr.user_id', $admin_id)
        ->orderBy('rr.restlen');
    // ->select(['rr.*'])

    // ->groupBy('rm.film_type_id')

    $data = $model->first(['rr.*', 'rm.film_type_id']);
    return $data;
}

/*
 * 获取符合长度要求的数据
 * 可以超过，不会低于
 * 返回卷号、rid、rlength、film_type_id
 * */
function getRRV2($film_type_id, $length = 1, $admin_id = null)
{
    /*if ($length > 200000) {
        return abort(500);
    }*/
    $admin_id = (int) $admin_id ?: gui();
    $num = 200;
    $model = DB::table('roll_restlen as rr')
        ->leftJoin('roll_master as rm', 'rm.roll_number', 'rr.roll_number')
        ->where('rm.film_type_id', $film_type_id)
        ->whereNull('rm.deleted_at')
        ->whereNull('rr.deleted_at')
        ->where('rr.restlen', '>', 0)
        ->where('rr.user_id', $admin_id)
        ->orderBy('rr.restlen')
        ->select(['rr.*', 'rm.film_type_id']);

    $data = $model->limit($num)
        ->get();
    $l = Arr::pluck($data, 'restlen');
    $tlen = array_sum($l);
    while ($tlen < $length && $num < 2000) {
        $num = $num + 100;
        $data = $model->limit($num)
            ->get();
        $l = Arr::pluck($data, 'restlen');
        $tlen = array_sum($l);
    }
    return $data;
}

/*
 * 根据模型号
 * 返回卷号、rid、rlength、film_type_id
 * */
function getRRV3($film_type_id)
{
    $admin_id = gui();
    $admin_type = gut();
    if ($admin_type == 1) {
        $admin_id = 1;
    }
    $data = DB::table('roll_restlen as rr')
        ->leftJoin('roll_master as rm', 'rm.roll_number', 'rr.roll_number')
        ->where('rm.film_type_id', $film_type_id)
        ->where('rr.user_id', $admin_id)
        ->where('rr.restlen', '>', 0)
        ->whereNull('rm.deleted_at')
        ->whereNull('rr.deleted_at')
        ->orderBy('rr.restlen')
        ->select([
            'rr.restlen',
            'rr.roll_number',
            'rm.film_type_id',
        ])
        ->get();
    return $data;
}

/*
 * 删除专车专用套件*/
function deleteNewPrecut($id)
{
    $admin_id = gui();
    $admin_type = gut();
    $model = NewPrecut::find($id);
    if (empty($model) || empty($model->id)) {
        return fs404('专车专用套件信息不存在！' . $id);
    }
    if ($admin_type == 2) {
        if ($model->created_by != $admin_id) {
            return fs404('无操作权限！');
        }
    }
    // 已分配不可以删除
    if (!empty($model->user_id) && $model->user_id != $admin_id) {
        return fs403('专车专用套件已分配，无法删除！');
    }
    if ($model->status == 1) {
        return fs403('专车专用套件已安装，无法删除！');
    }
    NewPrecutFpart::where('precut_id', $model->id)->delete();
    $pvcs = NewPrecutCoverage::where('precut_id', $model->id)->get();
    foreach ($pvcs as $k => $v) {
        plusRestlen($model->created_by, $v->roll_number, $v->length);
    }
    NewPrecutCoverage::where('precut_id', $model->id)->delete();
    $alogs = alogs('专车专用套件', '删除', $model->id, null, $model);
    $bool = $model->delete();
    return fs200('专车专用套件信息删除成功');
}

/*
 * 获取省代列表*/
function gDV1()
{
    $user_type = session('admin.user_type');
    $user_id = session('admin.id');
    $model = Admin::where('status', 1)
        ->where('user_type', 2);

    if ($user_type == 4) {
        $users = DB::table('users_relation')
            ->where('user_id', $user_id)
            ->get();
        if (empty($users)) {
            return [];
        }
        $userIdArr = [];
        foreach ($users as $user) {
            $userIdArr[] = $user->belong_user_id;
        }
        $model->whereIn('id', $userIdArr);
    }
    $data = $model
        ->orderBy('status')
        ->orderBy('unique_id')
        ->select(['id', 'abbr'])
        ->get();
    return $data;
}

function addNPAssign($precut_id, $sold_by_user_id, $sold_to_user_id, $type = 1)
{
    $sales = new \App\Models\NewPrecutAssign();
    $sales->precut_id = $precut_id;
    $sales->sold_by_user_id = $sold_by_user_id;
    $sales->sold_to_user_id = $sold_to_user_id;
    $sales->created_by = gui();
    $sales->type = $type;
    $sales->save();
    $activity = '分配';
    if ($type == 2) {
        $activity = '退货';
    }
    alogs('专车专用套件', $activity, $precut_id, $sales, null);
    return $sales->id;
}
/*
 * 传入质保ID
 * 获取用料长度最大的卷号*/
function gMR($id)
{
    $warranty = Warranty::find($id);
    if (empty($warranty->precut_id)) {
        $coverage = WarrantyToVehicleCoverage::where('warranty_id', $id)
            ->get();
        $wRoll = [];
        foreach ($coverage as $k => $v) {
            $wRoll[$v->roll_number] = @$wRoll[$v->roll_number] + $v->length;
        }
        arsort($wRoll);
        $mRoll = '';
        if (!empty($wRoll)) {
            $mRoll = array_keys($wRoll)[0];
        }
        return $mRoll;
    } else {
        return getNPid($warranty->precut_id);
    }
}

/*
 * 传入质保ID
 * 获取安装部位名称、模型号名称
 * */
function gWFP($id)
{
    $warranty = Warranty::find($id);
    if (empty($warranty->precut_id)) {
        $data = WarrantyToVehicleCoverage::where('warranty_id', $id)
            ->get([
                'part_id',
                'film_type_id',
            ]);
        $res = [];

        foreach ($data as $k => $v) {
            $film_type = ts('film_type_master.' . $v->film_type_id);
            if (empty($film_type)) {
                $roll = getRollsMasterByRollNumber($v->roll_number);
                $film_type = ts('film_type_master.' . $roll->film_type_id);
            }
            $v->part = ts('part_master.' . $v->part_id);
            $v->film_type = $film_type;
            $res[] = $v;
        }
        return $res;
    } else {
        $data = NewPrecutFpart::where('precut_id', $warranty->precut_id)
            ->get([
                'part_id',
                'film_type_id'
            ]);
        $res = [];

        foreach ($data as $k => $v) {
            $v->part = ts('new_precut_part.' . $v->part_id);
            $v->film_type = ts('film_type_master.' . $v->film_type_id);
            $res[] = $v;
        }
        return $res;
    }
}
/*
 * 获取地区ID*/
function getRegionId($name, $array)
{
    return @$array[$name];
}

/*
 * 获取省份ID*/
function getProvinceId($name, $array)
{
    return @$array[$name];
}

/*
 * 获取城市ID*/
function getCityId($name, $array)
{
    return @$array[$name];
}
/*
 * 获取地区列表*/
function getRegionList()
{
    $data = RegionMaster::get();
    $res = [];
    foreach ($data as $k => $v) {
        $res[$v->english_value] = $v->id;
        $res[$v->traditional_chiness_value] = $v->id;
        $res[$v->simplified_chiness_value] = $v->id;
    }
    return $res;
}

/*
 * 获取省份列表*/
function getProvinceList()
{
    $data = ProvinceMaster::get();
    $res = [];
    foreach ($data as $k => $v) {
        $res[$v->english_value] = $v->id;
        $res[$v->traditional_chiness_value] = $v->id;
        $res[$v->simplified_chiness_value] = $v->id;
    }
    return $res;
}

/*
 * 获取城市列表*/
function getCityList()
{
    $data = Cities::get();
    $res = [];
    foreach ($data as $k => $v) {
        $res[$v->english_value] = $v->id;
        $res[$v->traditional_chiness_value] = $v->id;
        $res[$v->simplified_chiness_value] = $v->id;
    }
    return $res;
}

/*
 * 获取城市列表*/
function getMakeList()
{
    $data = MakeMaster::get();
    $res = [];
    foreach ($data as $k => $v) {
        $res[$v->english_value] = $v->id;
        $res[$v->traditional_chiness_value] = $v->id;
        $res[$v->simplified_chiness_value] = $v->id;
    }
    return $res;
}
/*
 * 获取城市列表*/
function getModelList()
{
    $data = ModelMaster::get();
    $res = [];
    foreach ($data as $k => $v) {
        $res[$v->english_value] = $v->id;
        $res[$v->traditional_chiness_value] = $v->id;
        $res[$v->simplified_chiness_value] = $v->id;
    }
    return $res;
}
/*
 * 获取数据字典列表*/
function getDictList($table)
{
    $res = [];
    $data = [];
    if (in_array($table, ['region', 'region_master'])) {
        $data = RegionMaster::get();
    }
    if (in_array($table, ['province', 'province_master'])) {
        $data = ProvinceMaster::get();
    }
    if (in_array($table, ['city', 'cities'])) {
        $data = Cities::get();
    }
    if (in_array($table, ['make', 'make_master'])) {
        $data = MakeMaster::get();
    }
    if (in_array($table, ['part', 'part_master'])) {
        $data = PartMaster::get();
    }
    if (in_array($table, ['model', 'model_master'])) {
        $data = ModelMaster::get();
    }
    foreach ($data as $k => $v) {
        $res[$v->english_value] = $v->id;
        $res[$v->traditional_chiness_value] = $v->id;
        $res[$v->simplified_chiness_value] = $v->id;
    }
    return $res;
}

/*
 * 获取数据字典列表*/
function getUsersList($creator_id = 0)
{
    $model = DB::table('users')->select(['id', 'abbr', 'status', 'deleted_at']);
    if (!empty($creator_id) && $creator_id != 1) {
        $model->where('creator_id', $creator_id);
    }
    $data = $model->get();
    $res = [];
    /*优先获取启用用户*/
    foreach ($data as $k => $v) {
        if ($v->status == 1 && $v->deleted_at === null) {
            $res[$v->abbr] = $v->id;
        }
    }
    /*获取停用用户*/
    foreach ($data as $k => $v) {
        if (!$v->deleted_at === null) {
            if (empty($res[$v->abbr])) {
                $res[$v->abbr] = $v->id;
            }
        }
    }
    /*获取全部用户*/
    foreach ($data as $k => $v) {
        if (empty($res[$v->abbr])) {
            $res[$v->abbr] = $v->id;
        }
    }
    return $res;
}

function getNewPrecutIds($precut_ids)
{
    $data = NewPrecut::whereIn('precut_id', $precut_ids)
        ->get(['id', 'precut_id', 'status', 'user_id']);
    $res = [];
    foreach ($data as $k => $v) {
        $res[$v->precut_id] = [
            'id' => $v->id,
            'precut_id' => $v->precut_id,
            'status' => $v->status,
            'user_id' => $v->user_id,
        ];
    }
    return $res;
}
/*
 * 获取专车专用套件ID*/
function getNPid($id)
{
    $model = NewPrecut::find($id);
    return @$model->precut_id ?: '';
}
/*
 * 获取专车专用套件用料长度*/
function getNPLen($id)
{
    $length = NewPrecutCoverage::where('precut_id', $id)->sum('length');
    return $length ?: 0;
}

/*
 * 获取用户及下属经销商尚未安装的专车专用套件
 * 不获取管理员信息
 * */
function getNDPDs($user_id)
{
    return DB::table('new_precut')
        ->whereIn('user_id', function ($query) use ($user_id) {
            $query->select('id')->from('users')
                ->where('users.id', $user_id)
                ->orWhere('creator_id', $user_id);
        })
        ->where('status', '!=', 1)
        ->whereNull('deleted_at')
        ->get(['id', 'precut_id']);
}

/*
 * 获取省代名称
 * 不获取管理员信息
 * */
function getSdmc($user_id)
{
    $sdmc = '';
    $admin = DB::table('users')->find($user_id);
    if (empty($admin) || empty($admin->id)) {
        return $sdmc;
    }
    if ($admin->user_type != 3) {
        $sdmc = @$admin->abbr ?: '';
    } else {
        $sd = DB::table('users')->find($admin->creator_id);
        $sdmc = @$sd->abbr ?: '';
    }
    return $sdmc;
}

function getPage(string $title, string $pageName, string $url = '')
{
    return [
        'page_name' => $pageName,
        'title' => $title,
        'breadcrumb' => [
            [
                'text' => '数据报表',
                'url' => $url
            ]
        ],
    ];
}

function warrantyPart($model): bool
{
    $parts = [];
    $rolls = request()->input('rolls');
    if (empty($rolls) && !is_array($rolls)) {
        return false;
    }
    foreach ($rolls as $k => $v) {
        $roll = getRollsMasterByRollNumber($v['roll_number']);
        $parts[] = [
            'part_id' => $v['part'],
            'roll_number' => $v['roll_number'],
            'length' => $v['length'],
            'width' => $roll->width,
            'film_type_id' => $roll->film_type_id,
            'precut_or_manual' => $v['prect_or_manual'],
            'warranty_id'   => $model->id,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ];
    }
    // 删除卷膜
    if (!empty($parts)) {
        WarrantyToVehicleCoverage::where('warranty_id', $model->id)->delete();
        return DB::table('warranty_to_vehicle_coverage')->insert($parts);
    }

    return false;
}

function isMonth($str)
{
    $format = "Y-m";
    $date = DateTime::createFromFormat($format, $str);
    return $date && $date->format($format) == $str;
}

//推送质保状态
function pushWarrantyStatus($dearId, $warranty_id,$approved,$reason = ''){
    try {
        switch ($approved) {
            case 1:
                $status = 2;
                break;
            case 2:
                $status = 3;
                break;
            default:
                return false;
        }
        $dealer = Admin::withTrashed()->where('id', $dearId)->first();
        if (empty($dealer)) {
            return false;
        }
        $storeCode = $dealer->unique_id;
        $url = "http://cmn.xpel-et.com:8090/Home/Type/qualityStatus";
        $data = [
            'store_code' => $storeCode,
            'warranty_id' => $warranty_id,
            'status' => $status,
            'reason' => $reason,
        ];
        $res = send_post($url, $data);
        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code'] == 200) {
            return true;
        }
        Log::error('质保推送失败：' . $res['msg']);
        return false;
    }catch (Exception $e){
        Log::error('质保推送失败：' . $e->getMessage());
        return false;
    }
}

function send_post($url, $post_data)
{
    $postData = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postData,
            'timeout' => 15 * 60 // 超时时间（单位:s）
        )
    );
    $context = stream_context_create($options);
    return file_get_contents($url, false, $context);
}

function checkRollShow($roll_number)
{
    $w = DB::table('roll_master as r')
        ->leftJoin('film_type_master as f', 'f.id', 'r.film_type_id')
        ->where('r.roll_number', $roll_number)
        ->first();
    if (!$w) {
        return 0;
    }
    if($w->product_type_id==2){
        return 1;
    }
    return $w->is_show;
}

/*
 * 获取label对应内容*/
function getLabelInfo($label, $info)
{
    // 标签=>翻译前缀 映射关系
    $labelPrefixMap = [
        'region_id' => 'region_master.',
        'province_id' => 'province_master.',
        'city' => 'cities.',
    ];

    if (isset($labelPrefixMap[$label])) {
        return translateInfo($info, $labelPrefixMap[$label]);
    }

    $specialLabels = ['mdtype', 'zsdj', 'jsdj', 'jshudj'];
    if (in_array($label, $specialLabels)) {
        return translateInfo($info, $label);
    }
    //上级
    if ($label=='creator_id') {
        if (is_array($info)) {
            return implode(' ', array_map(function($item)  {
                $w = Admin::where('id', $item)->first();
                return $w?$w['company_name']:'';
            }, $info));
        }else{
            $w = Admin::where('id', $info)->first();
            return $w?$w['company_name']:'';
        }
    }

    if ($label=='top100') {
        if($info==1){
            $w =ts('GOLD');
        }else if($info==2){
            $w =ts('SILVER');
        }else{
            $w =ts('NO');
        }
        return $w;
    }
    return $info;
}

/**
 * getLabelInfo辅助方法：处理信息的翻译
 */
function translateInfo($info, $prefix)
{
    if (is_array($info)) {
        return implode(' ', array_map(function($item) use ($prefix) {
            return ts($prefix . $item);
        }, $info));
    }

    return ts($prefix . $info);
}